LeetCode 19. Remove Nth Node From End of List(删除单链表倒数第N个结点)

题目描述:

    Given a linked list, remove the nth node from the end of list and return its head.

例子:

   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.

分析:
    题意:给定一个单链表,移除它的倒数第n个结点并返回。

LeetCode 19

    思路:为了方便操作,我们用指针h建立一个空结点(方便指针pre的操作,同时也为了应对“删除第一个结点”这种情况),使其next指针指向指针head。初始化指针pre指向指针h,指针p和q指向指针head,接下来分三步:①指针q向前移动(n-1)步;②指针pre、p、q同时向前移动,直到指针q到达尾结点;③修改指针pre指向结点的next指针指向指针p指向结点的next指针指向的结点,并删除指针p指向的结点,最后返回指针h指向结点的next指针。

代码:

#include <bits/stdc++.h>

using namespace std;

struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x): val(x), next(NULL){}
};

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
		// Exceptional Case: 
		if(!head){
			return head;
		}
        ListNode* h = new ListNode(-1), *pre = h, *p = head, *q = head;
		h->next = head;
		for(int i = 1; i <= n - 1; i++){
			q = q->next;
		}
		while(q->next){
			q = q->next;
			pre = pre->next;
			p = p->next;
		}
		pre->next = p->next;
		delete(p);
		return h->next;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值