LeetCode/206. Reverse Linked List.md
2018-09-22 19:27:37 +08:00

1.7 KiB
Raw Blame History

206. Reverse Linked List

思路

思路一:迭代

先设置一个头结点List_head其next指向NULL。然后从待翻转链表中一次取一个节点p出来将p的next指向List_head的nextList_head的next指向p。 循环上述操作直到p为NULL。

思路二:递归

也可以采用递归的方式:

  • 递归出口若head == NULL 或者 head -> next == NULL直接返回head即可
  • 递归主体用q记录head的下一个节点然后令p等于reverseList(q)则p的最后一个非空节点就是q将q的next令为headhead的next令为NULL再返回p即可。

C++

思路一

/**
 * 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) {
        ListNode *List_head = new ListNode(0);
        List_head -> next = NULL;
        
        ListNode *p = head, *tmp;
        while(p){
            tmp = p -> next;
            p -> next = List_head -> next;
            List_head -> next = p;
            p = tmp;
        }
        return List_head -> 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, *q;
        
        q = head -> next;
        p = reverseList(q);
        q -> next = head;
        head -> next = NULL;
        return p;
    }
};