zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

链表节点 删除 倒数第
2023-09-11 14:19:17 时间
			采用两个指针,对前指针,使其先走出N步,随后两个指针同时前进,当前指针到达链表尾部时,后指针到达倒数第N个节点的位置。

			注意:删除时注意待删除节点为头结点时的情况。


			/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 */

			class Solution {
			public:
				/**
				 *
				 * @param head ListNode类
				 * @param n int整型
				 * @return ListNode类
				 */
				ListNode* removeNthFromEnd(ListNode* head, int n) {
					// write code here
					ListNode* newhead = new ListNode(0);					//必须定义新的空头
					newhead->next = head;									//新空头->next  = head
					head = newhead;											//head = newhead     这句不懂

					ListNode *fast = head;
					ListNode *slow = head;

					if (head == NULL)
					{
						return head;
					}
					for (int i = 0; i < n; i++)
					{
						fast = fast->next;
					}
					while (fast->next != NULL)
					{
						fast = fast->next;
						slow = slow->next;

					}
					ListNode *node = slow->next;							//删除节点的三句话 (1)定义节点=下一个
					slow->next = slow->next->next;							//				   (2)下一个=下一个的下一个
					free(node);												//				   (3)释放定义的节点
					return  newhead->next;									// 这句很重要。我试了如head、newhead都不对


				}
		};