关于链表 救救孩子吧
#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这个函数里返回headhead在这个函数里没有做处理啊将地址值赋值给cur 通过逻辑确实能将重复的地方给抹去 但是好像返回head 这不就是怎么传进来 怎么传出去嘛
大神们给解答一下! 本帖最后由 jhq999 于 2022-5-30 23:22 编辑
struct Node *deleteDup(struct Node *head)
{
if(head == NULL)
{
return head;
}
struct Node *cur = head;
while (cur&&cur->next)
{
struct Node *p=cur;
while (p->next)
{
if(cur->value==p->next->value)
{
struct Node *tmp = p->next;
p->next=p->next->next;
free(tmp);
}
else
p= p->next;
}
cur = cur->next;
}
return head;
} jhq999 发表于 2022-5-30 23:11
我的意思是 将head这个地址值赋值给cur这个指针 cur这个链表内的地址改变 不会影响head里面的链表对嘛?
cur = haed;
cur = cur->next;
head的头指针有跟随cur=cur->next而改变嘛 youxixingzhet 发表于 2022-5-31 10:04
我的意思是 将head这个地址值赋值给cur这个指针 cur这个链表内的地址改变 不会影响head里面的链表对 ...
head和cur是不同的变量,只不过cur初始值和head相同,head当然不会随cur的改变而改变,同理cur也不会随head的改变而改变 jhq999 发表于 2022-5-31 11:23
head和cur是不同的变量,只不过cur初始值和head相同,head当然不会随cur的改变而改变,同理cur也不会随he ...
按理说: cur = head的时候cur和head指向同一个地址,然后你改变cur的地址就相当于改变了head的地址
本帖最后由 jhq999 于 2022-5-31 15:41 编辑
Daume 发表于 2022-5-31 13:12
按理说: cur = head的时候cur和head指向同一个地址,然后你改变cur的地址就相当于改变了head的地址
看来你还明白指针和指针指向的内容。
head=123;
cur=head;
cur=234;
head还是等于123
至于你说的改变是解引用
head=123;
cur=head;
*head=1;
*cur=2;/////这时候*head=2
页:
[1]