鱼C论坛

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

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

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

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

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

x
Code:
#include <stdio.h>

struct Node{

    int val;
    struct Node *next;

};

struct Node* reverseList(struct Node * hd){ 

    struct Node *newHead = NULL;

    while(hd){

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

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

        newHead = hd;// newhead变成 a

        hd = next;// hd 变成 b
    }


    return newHead;

}

int main() {

    struct Node a;
    struct Node b;
    struct Node c;
    struct Node d;
    struct Node e;

    a.val = 10;
    b.val = 20;
    c.val = 30;
    d.val = 40;
    e.val = 50;

    a.next = &b;
    b.next = &c;
    c.next = &d;
    d.next = &e;
    e.next = NULL;

    struct Node *head = &a;

    while(head){

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

        head = head->next;

    }

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

    struct Node *head1 = &a;

    struct Node *ptr = reverseList(head1);


    while(ptr){

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

        ptr = ptr->next;

    }

    return 0;
}


output:
10
20
30
40
50
--------------
50
40
30
20
10

本帖被以下淘专辑推荐:

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

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-9-20 13:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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