[LeetCode]19. Remove Nth Node From End of List

来源:互联网 发布:linux xz 编辑:程序博客网 时间:2024/06/16 04:44

题目描述:Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

解题思路:既然考虑了n为有效的输入,就不用判断n是否小于链表的长度。删除倒数第n个节点。需要在头结点前设置一个节点,让follow指针每次前进的时候都比p指针慢一个节点,方便删除倒数第n个节点。

public ListNode removeNthFromEnd(ListNode head, int n) {        if(head==null)return null;        //创建preHead,避免第一个节点为就为删除的节点。        ListNode preHead = new ListNode(0);        preHead.next = head;        ListNode p = head;        //保证follow在p的后一个节点同步移动        ListNode follow = preHead;        for(int i=0;i<n;i++){            p=p.next;           }        while(p!=null){            p=p.next;            follow = follow.next;        }        follow.next = follow.next.next;         return preHead.next;    }
原创粉丝点击