Remove Nth Node From End of List

1、遇到鏈表的問題,首先要記得判斷head==NULL;
2、鏈表中查找某個結點時,通常用三個輔助指針來表示;
這裏寫圖片描述
題目:
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.
思路:
1、設置三個輔助指針,指針p和q的間隔爲n-1;
2、將設置好距離的指針向後移動,直至最後一個指針指到鏈表的最後一個位置爲止;
3、判斷所要刪掉的是否爲頭結點(pPre==NULL),是則刪掉頭結點,否則刪掉p指針所指的結點;
代碼:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(head==NULL) return NULL;
        ListNode *pPre=NULL;
        ListNode *p=head;
        ListNode *q=head;

        for(int i=0;i<n-1;i++)
        {
            q=q->next;
        }

        while(q->next)
        {
            pPre=p;
            p=p->next;
            q=q->next;
        }

        if(pPre==NULL)
        {
            head=p->next;
            delete p;
        }
        else
        {
            pPre->next=p->next;
            delete p;
        }
        return head;
    }
};
發佈了19 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章