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个结点。
思路:
设置两个指针都指向Head。
开始让一个指针先跑n步,后来另外一个指针也开始跑,当第一个到达终点时,第二个也恰好到达删除结点。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int i=0;
ListNode p1 = head;
ListNode p2 = head;
ListNode removeNode = head;
while(p1!=null){
p1=p1.next;
i++;
if(i>n)
{
p2= removeNode;
removeNode=removeNode.next;
}
}
if(removeNode==head)
return head.next;
else
{
p2.next=removeNode.next;
return head;
}
}
}
总结:
这道题目不算难,可是我却做了很久。自刷题来一个多月了,虽然多少有提升点,但还是很弱。可是再弱的现在也不能成为放弃的借口!
有做,总是比放弃好。
加油!