Leetcode 19. Remove Nth Node From End of List

題目

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個節點。
由于是鏈表,只能從前向后尋找數據,所以先遍歷看一共多少數據,即可知道要移除的倒數第幾個數字是正數的第幾個數字。
之后尋找該幾點和其前節點,然后替換next指針即可,C代碼如下,已通過。
也可以使用兩個指針,先讓一個走n步,另一個接著走。那么當第一個指針達到鏈表尾部時候,第二個指針指向第n個節點。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* removeNthFromEnd(struct ListNode* head, int n) {
    struct ListNode * p=head, *q=head;
    int length=0;
    while(p!=NULL)
    {
        p=p->next;
        length++;
    }
    p=head;
    if(n>length)
        n=1;
    else
        n=length-n+1;
    while(n-1>0&&p->next!=NULL)
    {
        q=p;
        p=p->next;
        n--;
    }
    if(q==p)
    {
        head=head->next;
    }
    else
    {
        q->next=p->next;
    }
    return head;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容