链表

82 阅读1分钟

leetcode题目

206. 反转链表(简单)

92. 反转链表II(中等)

25. K个一组翻转链表(困难)

// 单链表节点的结构
public class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

反转链表

力扣第 206 题「反转链表」

  //递归法
    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        //递归调用  返回最后的节点作为反转链表的头节点
        ListNode last = reverseList(head.next);
        //1 -> 2 -> 3 -> 4 -> 5
        //  null<- 4 <- 5   null <- 3 <- 4 <- 5  ...
        // 最后 1 <- 2 <- 3 <- 4 <- 5
        head.next.next = head;
        head.next = null;
        return last;
    }


    //迭代法
    public ListNode reverseList2(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode next = cur.next;
            //当前节点的下一个节点指向之前的节点
            cur.next = pre;
            //当前节点变成之前的节点
            pre = cur;
            //下一个节点节点变成当前节点
            cur = next;
        }
        //当cur 为null的时候说明到了最后,pre为最后的节点
        return pre;
    }

反转部分链表

力扣第 92 题「反转链表 II」

 public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;

        ListNode pre = dummy;
        for (int i = 1; i < left; i++) {
            pre = pre.next;
        }
        ListNode cur = pre.next;
        ListNode next;
        // 按照当前的下一个,next的下一个,pre的下一个的顺序
        //1,2,3,4,5 -> 1 3 2 4 5
        // pre:1  cur:2   next:3
       
         //1 3 2 4 5 -> 1 4 3 2 5
        // pre:1   cur:2  next:4
        
        for (int i = 0; i < right - left; i++) {
            next = cur.next;
            cur.next = next.next;
            next.next = pre.next;
            pre.next = next;
        }
        return dummy.next;
    }

K个一组翻转链表

力扣第 25 题「K个一组翻转链表」

  public ListNode reverseKGroup(ListNode head, int k) {
        //判断是否超过k,超过需要分组反转,不超过直接返回
        ListNode temp = head;
        for (int i = 0; i < k; i++) {
            if (temp == null) {
                return head;
            }
            temp = temp.next;
        }

        //反转当前组
        ListNode pre = null;
        ListNode cur = head;
        int count = 1;
        while (cur != null && count <= k) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
            count++;
        }
        //数量超过,递归执行子问题
        if (count > k) {
            head.next = reverseKGroup(cur, k);
        }
        //pre 作为当前组的表头
        return pre;
    }