Seawolf 发表于 2019-8-1 11:09:57

LeetCode 206——反转链表

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
页: [1]
查看完整版本: LeetCode 206——反转链表