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.
先让p指向head,p往后移动n个节点,然后让q指向head,p和q一起后移直至p指向最后一个结点,则q指向的结点即是倒数第n个结点。当然,倒数第len(链表的长度)个结点是一个特殊情况,直接head=head.next即可。
public ListNode removeNthFromEnd(ListNode head, int n) { if(head==null) return head; ListNode pListNode=head,qListNode=head; int len=0; while(pListNode!=null) { len++; pListNode=pListNode.next; } if(n==len) { head=head.next; return head; } pListNode=head; for(int i=0;i<n;i++) { qListNode=qListNode.next; if (qListNode==null) break; } while(qListNode!=null&&qListNode.next!=null) { pListNode=pListNode.next; qListNode=qListNode.next; } qListNode=pListNode.next; pListNode.next=qListNode.next; return head; }
leetcode_19_Remove Nth Node From End of List
原文地址:http://blog.csdn.net/mnmlist/article/details/43446561