永发信息网

c语言数据结构,单链表的逆置

答案:1  悬赏:30  手机版
解决时间 2021-03-11 11:46
  • 提问者网友:爱了却不能说
  • 2021-03-10 15:51
c语言数据结构,单链表的逆置
最佳答案
  • 五星知识达人网友:低音帝王
  • 2021-03-10 16:28
#include
#include
typedef struct node
{
int data;
struct node*next;
}linklist;
linklist *creat()
{
linklist*head,*p,*t;
int i,n;
printf("input n:");
scanf("%d",&n);
head=(linklist*)malloc(sizeof(linklist));
t=head;
for(i=0;i {
p=(linklist*)malloc(sizeof(linklist));
scanf("%d",&p->data);
t->next=p;
t=p;
}
p->next=NULL;
return head;
}
void convert(linklist*head)
{
linklist*p,*t;
p=head->next;
head->next=NULL;//把每一个节点连接到头结点后面即可,后面的节点与在连接
while(p)
{
t=p;
p=p->next;
t->next=head->next;
head->next=t;

}

}
void output(linklist*head)
{
linklist*p=head->next;
while(p)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
void main()
{
linklist*p;
p=creat();
convert(p);
output(p);

}追问void convert(linklist*head)
{
linklist*p,*t;
p=head->next;
head->next=NULL;//把每一个节点连接到头结点后面即可,后面的节点与在连接
while(p)
{
t=p;
p=p->next;
t->next=head->next;
head->next=t;
就是这里不太懂
别人帮我找的,怎么也看不懂追答我觉得他写的这个不好理解,你就理解我写的这个吧!用t暂存p位置然后将t的next域指向后面的节点,head的next域指向t,然后p再后移,这样不就可以把每一个都放在头结点的后面了么?也就是把后面的依次拿到头结点后面然后用绳子连接(也就是next域)连接前面的,链接后面的!重复操作不就行了!追问最后一步是什么意思,为什么t还要赋给头指针追答将头指针的next域指向t:我做一个形象的比喻:有许多节点通过绳子(next)连在一起,你要把节点顺序给逆转,所以把第二个节点拿到第一个节点前面去,然后用绳子连接后面的
t->next=head->next
然后用绳子链接前面面的 head->next=t;//前后连接顺序不可以颠倒!我想颠倒你自己就觉得逻辑不对了!
然后你再将第三个节点拿到头结点后面,再重新将头结点与它连接,将它与头结点后面的节点链接这样他就在头结点与头结点原来后面的节点中间了。。。。。追问嗯嗯明白了谢谢你
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯