|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int value;
struct Node *next;
};
void insertNode(struct Node **head, int value)
{
struct Node *pre;
struct Node *cur;
struct Node *new;
cur = *head;
pre = NULL;
while (cur != NULL && cur->value < value)
{
pre = cur;
cur = cur->next;
}
new = (struct Node *)malloc(sizeof(struct Node));
if (new == NULL)
{
printf("内存分配失败!\n");
exit(1);
}
new->value = value;
new->next = cur;
if (pre == NULL)
{
*head = new;
}
else
{
pre->next = new;
}
}
void printNode(struct Node *head)
{
struct Node *cur;
cur = head;
while (cur != NULL)
{
printf("%d ", cur->value);
cur = cur->next;
}
putchar('\n');
}
struct Node *deleteDup(struct Node *head)
{
if(head == NULL)
{
return head;
}
struct Node *cur = head;
while (cur->next)
{
if (cur->value == cur->next->value)
{
cur->next = cur->next->next;
}
else
{
cur = cur->next;
}
}
return head;
}
int main(void)
{
struct Node *head = NULL;
struct Node *new = NULL;
int input;
while (1)
{
printf("请输入一个整数(输入-1表示结束):");
scanf("%d", &input);
if (input == -1)
{
break;
}
insertNode(&head, input);
}
printf("输入的单链表是:");
printNode(head);
printf("去重之后的单链表是:");
new = deleteDup(head);
printNode(new);
return 0;
}
没有想通为什么deleteDup这个函数里返回head head在这个函数里没有做处理啊 将地址值赋值给cur 通过逻辑确实能将重复的地方给抹去 但是好像返回head 这不就是怎么传进来 怎么传出去嘛
大神们给解答一下!
head和cur是不同的变量,只不过cur初始值和head相同,head当然不会随cur的改变而改变,同理cur也不会随head的改变而改变
|
|