題目爲 給定一個鏈表,刪除鏈表的倒數第 n 個節點,並且返回鏈表的頭結點。
示例:
給定一個鏈表: 1->2->3->4->5, 和 n = 2.
當刪除了倒數第二個節點後,鏈表變爲 1->2->3->5.
這裏要說明一下鏈表的結構,是如下結構,每個節點都指向下一個元素。
public class ListNode
{
public int val;
public ListNode next;
public ListNode(int x) { val = x; }
}
刪除一個元素的意思就是讓這個元素的上一個元素不再指向該元素,而是指向該元素的下一個元素,節點就從鏈表中刪除了。刪除B的意思如下所示圖示
A——>B——>C 轉換成A——>C
我的思路是使用遞歸,當元素沒有子節點的時候,代表該元素已經到結尾末端,這時遞歸向上返回時,我們依次加1,也就是末尾最後一個元素返回1,倒數第二個元素返回1+1,依次類推,當返回值res等於我們要刪除的倒數第n個節點減1的時候,就是刪除元素的下一個元素。當等於n+1的時候,是刪除元素的上一個元素。理解了思路,代碼如下。
public ListNode RemoveNthFromEnd(ListNode head, int n)
{
int all= GetDetailCount(head, n);
if (all==n)
{
return head.next;
}
liBegin.next = liAfter;
return head;
}
public ListNode liBegin = null;
public ListNode liAfter = null;
public int GetDetailCount(ListNode head,int n)
{
if (head.next == null)
{
if (1 == n - 1)
{
liAfter = head;
}
else if (1 == n + 1)
{
liBegin = head;
}
return 1;
}
else
{
int res = GetDetailCount(head.next, n) + 1;
if (res==n-1)
{
liAfter = head;
}
else if (res == n + 1)
{
liBegin = head;
}
return res;
}
}