leetcode 19.删除链表的倒数第N个节点

删除链表的倒数第N个节点 Remove Nth Node From End Of List

本人大四实习生,水平有限。有错望海涵指正。
题目


思路

-创建两个结点引用。第一个结点指向第n个结点,另一个结点指向第一个结点。然后一起往后移,第一个结点指向为null时,另一个结点指向的就是应该删除的结点。


代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        ListNode tip=head;
        ListNode forward=null;
        ListNode tail=head;
        int count=1;
        while(tail.next!=null){
            if(count==n){
                forward=tip;
                tip=tip.next;     
                tail=tail.next;
            }else{
                count++;
                tail=tail.next;
            }
        }
        if(tip==head){
            ListNode h=tip.next;
            tip.next=null;
            return h;
        }else{
            forward.next=tip.next;
            tip.next=null;
            return head;
        }
    }
}

只用了一次遍历

猜你喜欢

转载自blog.csdn.net/weixin_40421645/article/details/82623883