remove-nth-node-from-end-of-list

https://www.nowcoder.com/practice/f95dcdafbde44b22a6d741baf71653f6?tpId=46&tqId=29159&tPage=7&rp=7&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

思路一:用map容器记录某一号节点是什么节点,然后修改即可。
 


class Solution {
public:
	map<int, ListNode*>m;
    ListNode *removeNthFromEnd(ListNode *head, int n) {
		if(head == nullptr)
			return nullptr;
		
		ListNode * p = head;
		int num = 0;
		while(p){
			m[num] = p;//记录num号节点
			num++;
			p =p->next;
		}

		if(n > num)
			return head;

		if(n == num)
			return head->next;
		//被删除的节点是m[num - n],修改其前面的节点和后面的节点即可
		m[num - n - 1]->next = m[num - n + 1];//修改即可
		delete m[num - n];
		return head;


    }
};

思路二:快指针。先让快指针走n-1步,然后快慢指针一起走,直到快指针走到末尾,此时的慢指针指向的节点就是要删除的节点。



class Solution {
public:
    ListNode *removeNthFromEnd(ListNode *head, int n) {
        if(head == nullptr || n <= 0)
			return head;

		ListNode * slow = head, *fast = head;
		ListNode * pre = slow;//慢指针的前驱节点
		for(int i = 0; i < n - 1; i++){//快指针先走n-1步数
			if(fast == nullptr)
				break;
			fast = fast->next;

		}
		if(fast == nullptr )//n > 链表长度
			return head;

		while(fast->next){//快慢指针一起走
			fast =fast ->next;
			pre = slow;//记录慢指针前驱
			slow = slow->next;

		}
		if(pre == slow ){//删除的节点是一个节点
			return pre->next;//返回第二个节点即可
		}

		pre ->next = slow->next;//该指针域
		delete slow;
		return head;

    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值