算法-删除链表的倒数第N个节点

28 阅读1分钟

1,LeetCode19

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

/**
 * 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) {
        if(head == null){
            return head;
        }
        int length = 0;
        ListNode temp = head;
        while(temp != null){
            length++;
            temp = temp.next;
        }
        int index = length - n;
        if(index == 0){
            head = head.next;
            return head;
        }
        temp = head;
        for(int i = 1;i < index;i++){
            temp = temp.next;
        }
        if(temp.next == null){
            return head;
        }else {
            if(temp.next.next == null){
                temp.next = null;
                return head;
            }else {
                temp.next = temp.next.next;
                return head;
            }
        }
    }
}

2,面试题 02.07. 链表相交

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int sizeA = 0;
        int sizeB = 0;
        ListNode tempA = headA;
        ListNode tempB = headB;
        while(tempA != null){
            sizeA++;
            tempA = tempA.next;
        }
        while(tempB != null){
            sizeB++;
            tempB = tempB.next;
        }
        if(sizeA > sizeB){
            for(int i = 0;i < (sizeA - sizeB);i++){
                headA = headA.next;
            }
            while(headA != null && headA != headB){
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }else {
            for(int i = 0;i < (sizeB - sizeA);i++){
                headB = headB.next;
            }
            while(headB != null && headA != headB){
                headA = headA.next;
                headB = headB.next;
            }
            return headB;
         }
    }
}

3,LeetCode142

这道题也可以使用快慢指针的方式做,不过目前我没有看懂怎么做

/**
 * 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) {
        Set<ListNode> result = new HashSet();
        ListNode temp = head;
        while (temp != null) {
            if (result.contains(temp)) {
                return temp;
            } else {
                result.add(temp);
                temp = temp.next;
            }
        }
        return null;
    }
}