最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

单链表逆转【详解】

工作和技术 crifan 1867浏览 0评论

单链表逆转【详解】

void ReverseSingleLink(struct linknode *head)

{

if(head==NULL)

printf("The struct is null.n");

return ;

}

struct linknode *now; //the pointer,point to present linknode指向当前节点

struct linknode *post; //point to next linknode 指向下一个节点

struct linknode *tmp; //cache the post->next before its reset 用于后面的暂存post->next

//initialization初始化节点

now=head;

post=now->next;

now->next=NULL; //the end of the new link is NULL,转换后的链表的末端的值应为NULL

while(post!=NULL)

{

tmp=post->next;// cache post->next before reverse for latter use

post->next=now;//reverse the link direction

//keep correct relation after reverse

now=post;

post=tmp;

}

head=now;

return;

}//ReverseSingleLink

说明:

1如果前面的函数原型为 struct linkenode* ReverseSingleLink()

则,函数实现中最后的句子中,最后一行就该改为 return now;

2每次在while循环之前,前后链表节点的关系入下图

不过,特殊一点的是,第一次的while的循环的时候,now->next是由于前面的操作而为NULL.

而while循环中的操作单链表逆转操作之后的状态,如下图所示:

3.while循环中,其实主要的动作,就是其中那句转换链表方向:

post->next=now

不过

在此之前,要保存将要丢失的链接;

在此之后,要维持下一次操作之前的链表节点的关系.

转载请注明:在路上 » 单链表逆转【详解】

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
79 queries in 0.160 seconds, using 22.10MB memory