有序单链表删除重复元素(附加代码模式)(求指出错误在哪和一份正确代码)
算法2-25 有序单链表删除重复元素(附加代码模式)根据一个递增的整数序列构造有序单链表,删除其中的重复元素
本题是附加代码模式,主函数main的代码会自动附加在同学们提交的代码后面,请同学们在提交的时候注释掉自己的main函数。
main函数代码如下:
int main()
{
int n, status = -1;
while (cin >> n)
{
if (n == 0)
{
cout << "list is empty\n";
continue;
}
List list;
InitList(list);
for (int i = 0; i < n; i++)
{
int v;
cin >> v;
AddNode(list, v);
}
PrintList(list);
RemoveDuplicate(list);
PrintList(list);
DestroyList(list);
}
return 0;
}
单链表的结构体定义和相应的操作函数如下图所示:
struct Node
{
int data;
Node *next;
};
typedef Node *List;
int InitList(List list)
void DestroyList(List list)
int AddNode(List list, int data)
void PrintList(const List list)
我自己写了一份代码,但是提交结果显示Segmentation fault,这个错误出在哪里
代码如下
#include <iostream>
using namespace std;
struct Node
{
int data;
Node *next;
};
typedef Node *List;
int InitList(List list)
{
list = new Node;
list->next = NULL;
return 1;
}
void DestroyList(List list)
{
List p = list->next;
while (p)
{
List temp = p;
p = p->next;
delete temp;
}
delete list;
}
int AddNode(List list, int data)
{
List p = list, newnode = NULL;
while (p->next != NULL)
{
p = p->next;
}
newnode = new Node;
newnode->data = data;
p->next = newnode;
newnode->next = NULL;
return 1;
}
void PrintList(const List list)
{
List p = list->next;
while (p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void RemoveDuplicate(List list)
{
List p = list, last;
while (p)
{
last = p;
while (p && last->data == p->data)
{
List temp;
temp = p;
p = p->next;
if (temp != last)
{
free(temp);
}
}
last->next = p;
};
}
int main()
{
int n, status = -1;
while (cin >> n)
{
if (n == 0)
{
cout << "list is empty\n";
continue;
}
List list;
InitList(list);
for (int i = 0; i < n; i++)
{
int v;
cin >> v;
AddNode(list, v);
}
PrintList(list);
RemoveDuplicate(list);
PrintList(list);
DestroyList(list);
}
return 0;
}
本帖最后由 jhq999 于 2021-9-21 16:59 编辑
好好看看实参、形参相关的知识
int InitList(List &list)
{
list = new Node;
list->next = NULL;
return 1;
}
或者
int InitList(List *plist)
{
*plist = new Node;
*plist->next = NULL;
return 1;
}
页:
[1]