首页 > 其他分享 >链表——删除链表倒数第n个节点

链表——删除链表倒数第n个节点

时间:2022-10-27 09:57:17浏览次数:98  
标签:dummyHead ListNode fast next 链表 slow 节点 倒数第

class Solution 
{
public:

	ListNode* deleteback(ListNode*head, int n) 
	{
		ListNode* dummyHead = new ListNode(0);
		dummyHead->next = head;
		ListNode* fast = dummyHead;
		ListNode* slow = dummyHead;
		n++;
		while (n-- && fast != NULL)		// 注意是fast != NULL 而不是fast->next != NULL
		{
			fast = fast->next;
		}

		while (fast != NULL)
		{
			fast = fast->next;
			slow = slow->next;
		}

		slow->next = slow->next->next;
		return dummyHead->next;
                // C++还涉及之前开辟内存需要释放的问题
	}
};

标签:dummyHead,ListNode,fast,next,链表,slow,节点,倒数第
From: https://www.cnblogs.com/dh2021/p/16831090.html

相关文章