链表的经典算法题

链表是常见的数据结构之一,有许多经典的算法问题涉及到链表。以下是一些常见的链表算法题目:

  1. 反转链表(Reverse Linked List): 将链表反转,即将原链表的每个节点的指针方向反向。

  2. 判断链表是否有环(Linked List Cycle): 判断链表中是否存在环,即链表是否形成了一个闭环。

  3. 合并两个有序链表(Merge Two Sorted Lists): 将两个有序链表合并成一个有序链表。

  4. 删除链表中的重复元素(Remove Duplicates from Sorted List): 删除有序链表中的重复元素,使每个元素只出现一次。

  5. 删除链表的倒数第N个节点(Remove Nth Node From End of List): 删除链表中倒数第N个节点。

  6. 求链表的中间节点(Middle of the Linked List): 找到链表的中间节点,如果有两个中间节点,返回第二个。

  7. 交换相邻的节点(Swap Nodes in Pairs): 交换链表中相邻的节点,返回新的头节点。

  8. 回文链表(Palindrome Linked List): 判断链表是否是回文结构,即链表从前往后和从后往前读是相同的。

  9. 环形链表的起始节点(Linked List Cycle II): 找到环形链表的起始节点。

  10. 相交链表(Intersection of Two Linked Lists): 找到两个链表相交的起始节点。

这些题目涵盖了链表的基本操作、逆序、合并、查找中间节点、删除操作等常见场景。解决这些问题有助于熟练掌握链表的各种操作和应用。

反转链表(从前往后遍历,也可以从后往前递归)

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class ReverseLinkedList {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode current = head;

        while (current != null) {
            ListNode nextTemp = current.next;
            current.next = prev;
            prev = current;
            current = nextTemp;
        }

        return prev;
    }

    // 示例
    public static void main(String[] args) {
        // 创建链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        ReverseLinkedList solution = new ReverseLinkedList();
        ListNode reversedHead = solution.reverseList(head);

        // 打印反转后的链表
        while (reversedHead != null) {
            System.out.print(reversedHead.val + " ");
            reversedHead = reversedHead.next;
        }
    }
}

判断链表是否有环(双指针)

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class LinkedListCycle {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head.next;

        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false; // 若存在环,快指针不可能为null
            }

            slow = slow.next;
            fast = fast.next.next;
        }

        return true;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个有环的链表: 1 -> 2 -> 3 -> 4 -> 5 -> 2
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = head.next; // 5指向2,形成环

        LinkedListCycle solution = new LinkedListCycle();
        boolean hasCycle = solution.hasCycle(head);

        System.out.println("链表是否有环: " + hasCycle);
    }
}

合并两个有序链表 

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class MergeTwoSortedLists {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode dummy = new ListNode(0);
        ListNode current = dummy;

        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                current.next = l1;
                l1 = l1.next;
            } else {
                current.next = l2;
                l2 = l2.next;
            }
            current = current.next;
        }

        if (l1 != null) {
            current.next = l1;
        }

        if (l2 != null) {
            current.next = l2;
        }

        return dummy.next;
    }

    // 示例
    public static void main(String[] args) {
        // 创建两个有序链表: l1 = 1->2->4, l2 = 1->3->4
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);

        MergeTwoSortedLists solution = new MergeTwoSortedLists();
        ListNode mergedList = solution.mergeTwoLists(l1, l2);

        // 打印合并后的链表
        while (mergedList != null) {
            System.out.print(mergedList.val + " ");
            mergedList = mergedList.next;
        }
    }
}

删除链表中的重复元素

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class RemoveDuplicatesFromSortedList {
    public ListNode deleteDuplicates(ListNode head) {
        ListNode current = head;

        while (current != null && current.next != null) {
            if (current.val == current.next.val) {
                current.next = current.next.next; // 删除重复节点
            } else {
                current = current.next; // 指针移动到下一个节点
            }
        }

        return head;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个有序链表: 1 -> 1 -> 2 -> 3 -> 3
        ListNode head = new ListNode(1);
        head.next = new ListNode(1);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(3);

        RemoveDuplicatesFromSortedList solution = new RemoveDuplicatesFromSortedList();
        ListNode result = solution.deleteDuplicates(head);

        // 打印删除重复元素后的链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}

删除链表的倒数第N个节点(双指针)

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class RemoveNthNodeFromEnd {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = dummy;

        // 将快指针先移动N步
        for (int i = 0; i <= n; i++) {
            fast = fast.next;
        }

        // 同时移动慢指针和快指针
        while (fast != null) {
            slow = slow.next;
            fast = fast.next;
        }

        // 删除倒数第N个节点
        slow.next = slow.next.next;

        return dummy.next;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        RemoveNthNodeFromEnd solution = new RemoveNthNodeFromEnd();
        int n = 2;
        ListNode result = solution.removeNthFromEnd(head, n);

        // 打印删除倒数第N个节点后的链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}

求链表的中间节点(快慢指针)

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class MiddleOfTheLinkedList {
    public ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        return slow;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        MiddleOfTheLinkedList solution = new MiddleOfTheLinkedList();
        ListNode result = solution.middleNode(head);

        // 打印链表的中间节点
        System.out.println("链表的中间节点值为: " + result.val);
    }
}

交换相邻的节点 

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class SwapNodesInPairs {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode current = dummy;

        while (current.next != null && current.next.next != null) {
            ListNode first = current.next;
            ListNode second = current.next.next;

            // 交换相邻的节点
            first.next = second.next;
            second.next = first;
            current.next = second;

            current = current.next.next;
        }

        return dummy.next;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个链表: 1 -> 2 -> 3 -> 4 -> 5
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);

        SwapNodesInPairs solution = new SwapNodesInPairs();
        ListNode result = solution.swapPairs(head);

        // 打印交换相邻节点后的链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}

 回文链表

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class PalindromeLinkedList {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) {
            return true; // 空链表或只有一个节点的链表是回文链表
        }

        // 快慢指针找到链表中点
        ListNode slow = head;
        ListNode fast = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }

        // 反转后半部分链表
        ListNode reversedSecondHalf = reverseList(slow);

        // 比较前半部分和反转后的后半部分
        while (reversedSecondHalf != null) {
            if (head.val != reversedSecondHalf.val) {
                return false;
            }
            head = head.next;
            reversedSecondHalf = reversedSecondHalf.next;
        }

        return true;
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode current = head;

        while (current != null) {
            ListNode nextTemp = current.next;
            current.next = prev;
            prev = current;
            current = nextTemp;
        }

        return prev;
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个回文链表: 1 -> 2 -> 3 -> 2 -> 1
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(2);
        head.next.next.next.next = new ListNode(1);

        PalindromeLinkedList solution = new PalindromeLinkedList();
        boolean isPalindrome = solution.isPalindrome(head);

        System.out.println("链表是否是回文链表: " + isPalindrome);
    }
}

环形链表的起始节点 

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class LinkedListCycleII {
    public ListNode detectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;

        // 判断是否有环
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            if (slow == fast) {
                // 相遇点
                break;
            }
        }

        // 如果没有环,返回null
        if (fast == null || fast.next == null) {
            return null;
        }

        // 将一个指针移到链表头
        slow = head;

        // 两个指针同时前进,直到相遇点
        while (slow != fast) {
            slow = slow.next;
            fast = fast.next;
        }

        return slow; // 返回相遇点,即环的起始节点
    }

    // 示例
    public static void main(String[] args) {
        // 创建一个有环的链表: 1 -> 2 -> 3 -> 4 -> 5 -> 2
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);
        head.next.next.next = new ListNode(4);
        head.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next = head.next; // 5指向2,形成环

        LinkedListCycleII solution = new LinkedListCycleII();
        ListNode startOfCycle = solution.detectCycle(head);

        // 打印环的起始节点值
        System.out.println("环的起始节点值为: " + startOfCycle.val);
    }
}

相交链表

class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public class IntersectionOfTwoLinkedLists {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = getLength(headA);
        int lenB = getLength(headB);

        // 计算链表长度差
        int diff = Math.abs(lenA - lenB);

        // 将长链表的指针移动到与短链表相同长度的位置
        if (lenA > lenB) {
            headA = movePointer(headA, diff);
        } else {
            headB = movePointer(headB, diff);
        }

        // 同时遍历两个链表,找到相交节点
        while (headA != null && headB != null) {
            if (headA == headB) {
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }

        return null;
    }

    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }

    private ListNode movePointer(ListNode head, int steps) {
        for (int i = 0; i < steps; i++) {
            head = head.next;
        }
        return head;
    }

    // 示例
    public static void main(String[] args) {
        // 创建两个相交的链表
        // List A: 1 -> 2 -> 3 -> 6 -> 7
        // List B: 4 -> 5 -> 6 -> 7
        ListNode headA = new ListNode(1);
        headA.next = new ListNode(2);
        headA.next.next = new ListNode(3);
        headA.next.next.next = new ListNode(6);
        headA.next.next.next.next = new ListNode(7);

        ListNode headB = new ListNode(4);
        headB.next = new ListNode(5);
        headB.next.next = headA.next.next.next; // 相交于节点 6

        IntersectionOfTwoLinkedLists solution = new IntersectionOfTwoLinkedLists();
        ListNode intersectionNode = solution.getIntersectionNode(headA, headB);

        // 打印相交节点的值
        System.out.println("两个链表的相交节点值为: " + intersectionNode.val);
    }
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值