Skip to content

Latest commit

 

History

History
63 lines (59 loc) · 1.71 KB

206. Reverse Linked List.md

File metadata and controls

63 lines (59 loc) · 1.71 KB

思路

思路一:迭代

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

思路二:递归

也可以采用递归的方式:

  • 递归出口:若head == NULL 或者 head -> next == NULL,直接返回head即可;
  • 递归主体:用q记录head的下一个节点,然后令p等于reverseList(q),则p的最后一个非空节点就是q,将q的next令为head,head的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;
    }
};