题目
给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点。
c#
/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode RemoveNthFromEnd(ListNode head, int n) {
if(head==null||head.next==null)//当链表为空或链表元素只有一个时
{
return null;
}
ListNode a=head;//指针1
ListNode b=head;//指针2
ListNode c=head;//指针2的前一位
for(int i=0;i<n;i++)
{
a=a.next;
}
if(a==null)//说明此时,删除的链表元素为头指针
{
return b.next;
}
while(a!=null)
{
c=b;
a=a.next;
b=b.next;
}
c.next=b.next;
return head;
}
}