LeetCode(删除链表的倒数第N个节点)

题目描述:
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.
当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:
给定的 n 保证是有效的。
代码

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null||head.next==null){
           return  null;
        }
        ListNode p1=head;
        ListNode p2=head;
        for(int x=0;x<n;x++){
            p1=p1.next;
        }
        if(p1==null){
            return head.next;
        }
        while(p1.next!=null){
            p1=p1.next;
            p2=p2.next;
        }
        p2.next=p2.next.next;
        return head;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_40817827/article/details/89948832