反转链表

反转链表

-迭代

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while (curr != null) {
            ListNode tmp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tmp;
        }
        return prev;
    }
}

 

-递归

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null) return head;
        ListNode newHead = reverseList(head.next); // 找到当前最后一个元素,作为新的头结点
        head.next.next = head; // 将当前节点的下一个节点指向当前节点
        head.next = null; // 当前节点不再指定下一个节点,完成反转
        return newHead;
    }
}

 

K个一组反转链表

class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        // 逆转k个
        // 递归获得下一个头结点
        ListNode* curr = head;
        
        for(int i=0;i<k;i++){
            if(curr==NULL)
                return head;
            curr = curr->next;
        }
        
        ListNode* newNode = reverse(head,curr);
        head->next = reverseKGroup(curr,k);
        return newNode;
    }
    
    ListNode* reverse(ListNode* head, ListNode* last){
        // 最后一个节点不逆序
        ListNode* prev = last;
        
        while(head!=last){
            ListNode* tmp = head->next;
            head->next = prev;
            prev = head;
            head = tmp;
        }
        
        return prev;
    }
};

 

posted @ 2021-03-04 06:50  张王李代茂  阅读(69)  评论(0)    收藏  举报