`
ijavagos
  • 浏览: 1191980 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

链表逆序

阅读更多

http://blog.csdn.net/yxh0823/article/details/6080163

设链表节点为

  1. typedefstructtagListNode{
  2. intdata;
  3. structtagListNode*next;
  4. }ListNode,*List;

  1. typedefstructtagListNode{
  2. intdata;
  3. structtagListNode*next;
  4. }ListNode,*List;

要求将一带链表头List head的单向链表逆序。

分析:

1). 若链表为空或只有一个元素,则直接返回;

2). 设置两个前后相邻的指针p,q. 将p所指向的节点作为q指向节点的后继;

3). 重复2),直到q为空

4). 调整链表头和链表尾

示例:以逆序A->B->C->D为例,图示如下

实现及测试代码如下:

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. typedefstructtagListNode{
  4. intdata;
  5. structtagListNode*next;
  6. }ListNode,*List;
  7. voidPrintList(Listhead);
  8. ListReverseList(Listhead);
  9. intmain()
  10. {
  11. //分配链表头结点
  12. ListNode*head;
  13. head=(ListNode*)malloc(sizeof(ListNode));
  14. head->next=NULL;
  15. head->data=-1;
  16. //将[1,10]加入链表
  17. inti;
  18. ListNode*p,*q;
  19. p=head;
  20. for(inti=1;i<=10;i++)
  21. {
  22. q=(ListNode*)malloc(sizeof(ListNode));
  23. q->data=i;
  24. q->next=NULL;
  25. p->next=q;
  26. p=q;
  27. }
  28. PrintList(head);/*输出原始链表*/
  29. head=ReverseList(head);/*逆序链表*/
  30. PrintList(head);/*输出逆序后的链表*/
  31. return0;
  32. }
  33. ListReverseList(Listhead)
  34. {
  35. if(head->next==NULL||head->next->next==NULL)
  36. {
  37. returnhead;/*链表为空或只有一个元素则直接返回*/
  38. }
  39. ListNode*t=NULL,
  40. *p=head->next,
  41. *q=head->next->next;
  42. while(q!=NULL)
  43. {
  44. t=q->next;
  45. q->next=p;
  46. p=q;
  47. q=t;
  48. }
  49. /*此时q指向原始链表最后一个元素,也是逆转后的链表的表头元素*/
  50. head->next->next=NULL;/*设置链表尾*/
  51. head->next=p;/*调整链表头*/
  52. returnhead;
  53. }
  54. voidPrintList(Listhead)
  55. {
  56. ListNode*p=head->next;
  57. while(p!=NULL)
  58. {
  59. printf("%d",p->data);
  60. p=p->next;
  61. }
  62. printf("/n");
  63. }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics