c++将单向链表封装成类,求纠错

要求实现节点插入、查找和删除操作。
当用户从键盘输入"+字母"时,将该字母插入链表合适(链表按升序排列)的地方。
若用户输入"-字母",则在链表中查找该字母出现的所有地方并删除。
当用户输入*时,输出链表并结束。
//LinkList.h
#pragma once

struct Node {
char data;
struct Node* next;
};

class LinkList
{
public:
LinkList(void);
void insertAfter(Node* pos, Node* node);
bool deleteFirst(char c);
Node* getinsertPos(char c);
void print();
//void append(Node* head, Node* node);

private:
Node* head;
};

//LinkList.cpp
#include "LinkList.h"
#include <iostream>
using namespace std;

LinkList::LinkList(void) {
Node* head=NULL;
}

void LinkList::insertAfter(Node* pos, Node* node) {
if (pos==NULL) {
node->next=head;
head=node;
}
else {
node->next=pos->next;
pos->next=node;
}
}

bool LinkList::deleteFirst(char c){ //将字母第一次出现的节点删掉
Node* tmp=head;
int n=0;
if (head==NULL){
return false;
}
else{
if (head->data=c) {
while (head->data=c){
if (head->next==NULL)
delete head;
else{
tmp=head->next;
delete head;
head=tmp;
}
n++;
}
}
while (tmp->next!=NULL){
if (tmp->next->data=c){
tmp->next=tmp->next->next;
delete tmp->next;
n++;
}
else
tmp=tmp->next;
}
if (n==0)
return false;
else
return 1;
}
}

Node* LinkList::getinsertPos(char c) { //找该字母前一个节点的位置
Node* pos;
if (head->data>c || head==NULL)
pos=NULL;
else {
Node* tmp=head;
while (tmp->next!=NULL) {
if (tmp->next->data>c)
pos=tmp;
else
tmp=tmp->next;
}
if (tmp->next==NULL)
pos=tmp;
}
return pos;
}

void LinkList::print(){
Node* tmp;
tmp=head;
while (tmp!=NULL){
cout<<tmp->data;
tmp=tmp->next;
}
}

void main() {
LinkList list;
Node* node;
Node* pos;
char c;

cin>>c;

while (c!='*') {
if (c=='+') {
cin>>c;
node=new Node();
node->data=c;
node->next=NULL;
pos=list.getinsertPos(c);
list.insertAfter(pos,node);
}
if (c=='-') {
cin>>c;
while (list.deleteFirst(c));
}
}
list.print();
}
********************************
编译没有错误,运行时无论输入什么字母回车后均没有反应。

Node* LinkList::getinsertPos(char c) {   //找该字母前一个节点的位置
Node* pos;
if (head->data>c || head == NULL) // è¿è¡Œè¿™å¥ç¨‹åºå°±å´©æºƒäº†ã€‚首先head如果等于NULL,那么就不可以调用head->data,其他的暂时没看。到这就卡住了。
pos = NULL;
else {
Node* tmp = head;
while (tmp->next != NULL) {
if (tmp->next->data>c)
pos = tmp;
else
tmp = tmp->next;
}
if (tmp->next == NULL)
pos = tmp;
}
return pos;
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-05-07
这种东西需要自己调试的,靠肉眼看出错误是很难的追问

我们老师教过一点设断点调试,只会逐语句逐过程那样,但是不知道在哪设断点。。

相似回答