【LeetCode】19. 刪除連結串列的倒數第N個節點
阿新 • • 發佈:2018-12-16
題目描述
給定一個連結串列,刪除連結串列的倒數第 n 個節點,並且返回連結串列的頭結點。
示例
給定一個連結串列: 1->2->3->4->5, 和 n = 2. 當刪除了倒數第二個節點後,連結串列變為 1->2->3->5.
說明: 給定的 n 保證是有效的。
進階: 你能嘗試使用一趟掃描實現嗎?
解決方法
考察連結串列相關操作,首先找到倒數第n+1個節點,然後就是基本的連結串列刪除操作
/**
* 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) {
int len=0; //計算連結串列長度
ListNode *l1=head;
while(l1){
len++;
l1=l1->next;
}
if (len<=1) {head=NULL;return head;}//特殊情況1:只有一個節點
if (len==n) {head=head->next;return head;}//特殊情況2:刪除的是第一個節點
int count=0; //找到倒數第n+1個節點
ListNode *pos=head;
while(pos && count<len-n-1){
pos=pos->next;
count++;
}
ListNode *q=pos->next; //刪除倒數第n個節點(q位置)
pos-> next=q->next;
delete q;
return head;
}
};