Leetcode 回文链表(设计链表的反转)

链表的反转

  • 迭代方法的实现

图片引用于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。 
    }
};

  • 递归方法实现
/**
 * 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; 
    }
};

油管解释比较清楚的视频

posted @ 2019-07-01 19:23  小新猩  阅读(210)  评论(0编辑  收藏  举报