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;
		}
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章