关于链表的相关操作

1、寻找链表的中点

// 找到链表的中点(快慢指针)
    public ListNode getMidNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

 

2、翻转链表

// 翻转链表
    public ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while(curr != null) {
            ListNode node = curr.next;
            curr.next = prev;
            
            prev = curr;
            curr = node;
        }
        return prev;
    }

 

3、合并链表

// 合并链表
    public void merge(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }

 

综合例子143-重排链表

class Solution {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null) return ;

        // 找到链表的中点
        ListNode node = getMidNode(head);
        ListNode head1 = node.next;
        node.next = null;   // 将左右两部分断开
        // 翻转链表
        head1 = reverse(head1);
        // 合并
        merge(head, head1);
    }
    
    // 找到链表的中点(快慢指针)
    public ListNode getMidNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    // 翻转链表
    public ListNode reverse(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;

        while(curr != null) {
            ListNode node = curr.next;
            curr.next = prev;
            
            prev = curr;
            curr = node;
        }
        return prev;
    }

    // 合并链表
    public void merge(ListNode l1, ListNode l2) {
        ListNode l1_tmp;
        ListNode l2_tmp;
        while (l1 != null && l2 != null) {
            l1_tmp = l1.next;
            l2_tmp = l2.next;

            l1.next = l2;
            l1 = l1_tmp;

            l2.next = l1;
            l2 = l2_tmp;
        }
    }
}

 

上一篇:python 数据类型的内置方法


下一篇:css: scroll-table