题目:删除链表中倒数第n个结点(时间复杂度为O (n))
For example,
原始列表: 1->2->3->4->5, and n = 2.
删除后: 1->2->3->5.
这里所给出的n满足 n>=0&&n<=length of list.
思路:
找到倒数第(n+1)个结点,就能很容易地删除倒数第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) {
if(head==null||n==0)
return head;
ListNode front=head;
ListNode rear=head;
int num=1;
while(num<n+1)
{
rear=rear.next;
num++;
}
if(rear==null)
{
head=head.next;
}else
{
while(rear.next!=null)
{
rear=rear.next;
front=front.next;
}
front.next=front.next.next;
}
return head;
}
}