206. Reverse Linked List

来源:互联网 发布:淘宝考试答案50题2016 编辑:程序博客网 时间:2024/06/03 16:45

Reverse a singly linked list.

解题思路:

利用头节点,头插法。

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head) {        if (head == NULL) return NULL;        ListNode dummy(-1);        dummy.next = head;        ListNode *prev = &dummy;        ListNode *cur = head;        ListNode *next = head->next;        while (cur != NULL && next != NULL) {            cur->next = next->next;            next->next = prev->next;            prev->next = next;            next = cur->next;        }        return dummy.next;    }};

递归版本:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    ListNode* reverseList(ListNode* head) {        if (head == NULL || head->next == NULL) return head;        ListNode *p = reverseList(head->next);        head->next->next = head;        head->next = NULL;        return p;    }};
0 0
原创粉丝点击