鱼C论坛

 找回密码
 立即注册
查看: 1402|回复: 0

[学习笔记] LeetCode 206——反转链表

[复制链接]
发表于 2019-8-1 11:09:57 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
Code:

  1. #include <stdio.h>

  2. struct Node{

  3.     int val;
  4.     struct Node *next;

  5. };

  6. struct Node* reverseList(struct Node * hd){

  7.     struct Node *newHead = NULL;

  8.     while(hd){

  9.         struct Node *next = hd->next;//next 为b

  10.         hd->next = newHead;// a的下一个改成null

  11.         newHead = hd;// newhead变成 a

  12.         hd = next;// hd 变成 b
  13.     }


  14.     return newHead;

  15. }

  16. int main() {

  17.     struct Node a;
  18.     struct Node b;
  19.     struct Node c;
  20.     struct Node d;
  21.     struct Node e;

  22.     a.val = 10;
  23.     b.val = 20;
  24.     c.val = 30;
  25.     d.val = 40;
  26.     e.val = 50;

  27.     a.next = &b;
  28.     b.next = &c;
  29.     c.next = &d;
  30.     d.next = &e;
  31.     e.next = NULL;

  32.     struct Node *head = &a;

  33.     while(head){

  34.         printf("%d\n", head->val);

  35.         head = head->next;

  36.     }

  37.     printf("--------------\n");

  38.     struct Node *head1 = &a;

  39.     struct Node *ptr = reverseList(head1);


  40.     while(ptr){

  41.         printf("%d\n", ptr->val);

  42.         ptr = ptr->next;

  43.     }

  44.     return 0;
  45. }
复制代码



output:

  1. 10
  2. 20
  3. 30
  4. 40
  5. 50
  6. --------------
  7. 50
  8. 40
  9. 30
  10. 20
  11. 10
复制代码

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 23:04

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表