Leetcode palindrome list (list of reverse design)

List of reversal

  • Implement iterative approach

Picture cited in https://zhuanlan.zhihu.com/p/48405334

/**
 * 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 *curPe = NULL;
        ListNode *cur = head;
        ListNode *curNe;
        while(cur!=NULL)
        {
            curNe = cur->next;
            cur->next = curPe;
            curPe = cur;
            cur = curNe;
        }
        return curPe;
        //curpe cur curNe三个指针一直保持着这个次序,最后当cur指向NULL时,结束。反转后的头节点为curPe。 
    }
};
  • Recursive method to achieve
/**
 * 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; 
    }
};

Tubing explain more clearly video

Guess you like

Origin www.cnblogs.com/-xinxin/p/11116179.html