鱼C论坛

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

[学习笔记] Leetcode 92:反转链表 II

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

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

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

x
Code:

  1. #include <stdio.h>

  2. struct Node{

  3.     int val;

  4.     struct Node *next;

  5. };


  6. struct Node * reverseList1(struct Node *hd, int n, int m){

  7.     int change_len = m - n + 1;

  8.     struct Node * result = hd;

  9.     struct Node * pre_head = NULL;

  10.     while(hd && --n){

  11.         pre_head = hd;

  12.         hd = hd->next;

  13.     }

  14.     struct Node * modify_node_tail = hd;

  15.     struct Node * newHead = NULL;

  16.     while(hd && change_len){

  17.         struct Node *next = hd->next;

  18.         hd->next = newHead;

  19.         newHead = hd;

  20.         hd = next;

  21.         change_len = change_len -1;

  22.     }

  23.     modify_node_tail->next = hd;

  24.     if(pre_head){

  25.         pre_head -> next = newHead;
  26.     }
  27.     else{

  28.         result = newHead;
  29.     }


  30.     return result;
  31. }

  32. int main(void){

  33.     struct Node a;
  34.     struct Node b;
  35.     struct Node c;
  36.     struct Node d;
  37.     struct Node e;

  38.     a.val = 10;
  39.     b.val = 20;
  40.     c.val = 30;
  41.     d.val = 40;
  42.     e.val = 50;

  43.     a.next = &b;
  44.     b.next = &c;
  45.     c.next = &d;
  46.     d.next = &e;
  47.     e.next = NULL;

  48.     struct Node * head = &a;

  49.     while(head){

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

  51.         head = head->next;

  52.     }

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

  54.     struct Node * head_2 = &a;

  55.     int x = 2;

  56.     int y = 4;

  57.     struct Node *ptr_1 = reverseList1(head_2, x, y);

  58.     while(ptr_1){

  59.         printf("%d\n", ptr_1->val);

  60.         ptr_1 = ptr_1->next;

  61.     }

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

  63.     return 0;
  64. }
复制代码


Output:

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

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-28 00:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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