Day-1 反转链表

AcWing 35.反转链表

Day-1 反转链表_第1张图片

思路:

1.指针反向

2.维护相邻两个指针(a,b)

a,b同时向后跳一位

c = b - > next;

b - > next = a;

a = b, b = c;

3.直到a走到结尾

4.头结点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 || !head -> next ) //链表为空或只有一个点
            return head;
        auto a = head, b = a -> next;
        
        while(b)
        {
            auto c = b ->next;
            b -> next = a;
            a = b, b = c;
        }
        head -> next = NULL;
        return a;
    }
};

递归版本

1.用递归的方法,将第二个节点之后的链表反转,反转后第二个节点的指针指空;

2.让第二个节点的指针指向第一个节点

head -> next -> next = head;

3.最后让头结点指空

head -> next = NULL;

/**
 * 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 || !head -> next) return head;
        
        auto tail = reverseList(head -> next);
        head -> next -> next = head;
        head -> next = NULL;
        return tail;
    }
};

LeetCode 92.反转链表II

Day-1 反转链表_第2张图片

Day-1 反转链表_第3张图片

思路:头结点有可能会变,也可能不变,这时我们需要创建一个虚拟头结点。(虚拟头结点随意定义一个数值就可以)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseBetween(ListNode* head, int left, int right) {
        auto dummy =  new ListNode(-1);
        dummy -> next = head;
        auto a = dummy;
        for(int i = 0; i < left - 1; i ++ ) a = a -> next;
        auto b = a -> next, c = b -> next;
        for(int i = 0; i < right - left; i ++ )
        {
            auto d = c -> next;
            c -> next = b;
            b = c, c = d; 
        }
        a -> next -> next = c;
        a -> next = b;
        return dummy -> next;
    }
};

 

你可能感兴趣的:(链表)