【LeetCode】19. Remove Nth Node From End of List(C++)

地址:https://leetcode.com/problems/remove-nth-node-from-end-of-list/

题目:

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

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.

Follow up:
Could you do this in one pass?

理解:

最开始想到了快慢指针。。然而发现好像实现不了。
那就用最简单的两次遍历实现吧。

实现:

由于leetcode的链表都不带头节点,因此需要判断一下。或者简单粗暴的方式是加一个头节点。

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* p=head;
        int cnt=0;
        while(p){
            ++cnt;
            p=p->next;
        }
        if(n==cnt)
            return head->next;
        else{
            int times=cnt-n-1;
            p=head;
            while(times){
                p=p->next;
                --times;
            }
            p->next=p->next->next;
            return head;
        }

    }
};

一次遍历的实现

应该在某个地方看过这个方法?记不清了,还是看了一眼solution。。用两个指针,不过这里的快慢指针的移动速度是相同的。只是快指针比慢指针一开始多移动n+1次,这样最后快指针到n+1时,慢指针就到了null。为了方便删除节点,在开头加一个头节点。

class Solution {
public:
	ListNode* removeNthFromEnd(ListNode* head, int n) {
		ListNode* nHead = new ListNode(0);
		nHead->next = head;
		ListNode *slow = nHead, *fast = nHead;
		++n;
		while (n) {
			fast = fast->next;
			--n;
		}
		while (fast) {
			slow = slow->next;
			fast = fast->next;
		}
		slow->next = slow->next->next;
		head= nHead->next;
		return nHead->next;
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值