题:https://leetcode.com/problems/remove-nth-node-from-end-of-list/description/
Given a linked list, remove the n-th node from the end of list and return its head.
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.
除去链表倒数第1个元素。
双指针,设置 头结点,便于操作。
双循环, 先计算出 pfirst 指针的位置。然后 psecond 再跑。
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fNode = new ListNode(0); fNode.next = head; ListNode pfirst,psecond; pfirst = psecond = fNode; for(int i = 0 ; i<n && pfirst!=null;i++) pfirst = pfirst.next; while(pfirst.next!= null){ psecond = psecond.next; pfirst = pfirst.next; } psecond.next = psecond.next.next; return fNode.next; } }一个循环计数
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode fNode = new ListNode(0); fNode.next = head; ListNode pfirst,psecond; pfirst = psecond = fNode; int i = 0; while(pfirst.next!= null){ if(i==n) psecond = psecond.next; else i++; pfirst = pfirst.next; } psecond.next = psecond.next.next; return fNode.next; } }