关于链表的几道算法题

1.删除链表的倒数第n个节点

力扣icon-default.png?t=N7T8https://leetcode.cn/submissions/detail/482739445/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy=new ListNode(-1);
        dummy.next=head;

        //删除倒数第n个,先要找到倒数第N+1个节点
        ListNode x=findFromEnd(dummy,n+1);
        //删除倒数第n个几点
        x.next=x.next.next;
        return dummy.next;

    }

        // 返回链表的倒数第 k 个节点
        ListNode findFromEnd(ListNode head, int k) {
            ListNode p1 = head;
            // p1 先走 k 步
            for (int i = 0; i < k; i++) {
                p1 = p1.next;
            }
            ListNode p2 = head;
            // p1 和 p2 同时走 n - k 步
            while (p1 != null) {
                p2 = p2.next;
                p1 = p1.next;
            }
            // p2 现在指向第 n - k + 1 个节点,即倒数第 k 个节点
            return p2;
        }

}

2.环形链表

力扣icon-default.png?t=N7T8https://leetcode.cn/submissions/detail/482785908/

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast,slow;
        fast=slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow)break;
        }
        //上面的代码类似hasCycle函数
        if(fast==null||fast.next==null){
            //fast遇到空指针说明没有环
            return null;
        }
        //重新指向头节点
        slow=head;
        //快慢指针同步前进,相交点就是环的起点
        while(slow!=fast){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
        
    }
}

3.删除链表中的重复元素

力扣icon-default.png?t=N7T8https://leetcode.cn/submissions/detail/482785908/

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}                                       
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        //删除排序链表中的重复元素
        if(head==null)return null;
        ListNode slow=head,fast=head;
        while(fast!=null){
            if(fast.val!=slow.val){
                slow.next=fast;

                slow=slow.next;
            }
            fast=fast.next;
        }
        //断开和后面重复元素的链接
        slow.next=null;
        return head;

    }
}

你可能感兴趣的:(杂记,链表,数据结构,java)