LeetCode Remove Nth Node From End of List

链接: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/


给链表添加哨兵,使用差速指针找到待删除节点的上一个节点,删除即可 。

只需遍历一次链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
	public:
		ListNode *removeNthFromEnd(ListNode *head,int n)
		{
			ListNode *nil=new ListNode(0);
			nil->next=head;
			head=nil;
			ListNode *ft=head,*sl=head;
			for(int i=0;i<n;i++)
			{
				ft=ft->next;
			}
			while(ft->next!=NULL)
			{
				ft=ft->next;
				sl=sl->next;
			}
			nil=sl->next->next;
			sl->next=nil;
			return head->next;
		}
};




原文地址:https://www.cnblogs.com/frankM/p/4399425.html