LeetCode 19. 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
Note
Given n will always be valid.
Code
- java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode pNode = head, pTail = head, pre = null;
for(int i = 0; i < n; i++) {
pTail = pTail.next;
}
while(pTail != null) {
pTail = pTail.next;
pre = pNode;
pNode = pNode.next;
}
if(pre == null) {
return head.next;
} else {
pre.next = pNode.next;
}
return head;
}
}
Conclusion
- 链表的基本操作