Cover image for Interview Classic 150 Questions P19 Remove Nth Node From End of List

Interview Classic 150 Questions P19 Remove Nth Node From End of List


Timeline

Timeline

2025-11-20

init

linked list

Problem:

Fast and slow pointers, pay attention to the special case where the node to be deleted is the head node.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
struct ListNode {	int val;	ListNode *next;	ListNode()		: val(0)		, next(nullptr)	{	}	ListNode(int x)		: val(x)		, next(nullptr)	{	}	ListNode(int x, ListNode *next)		: val(x)		, next(next)	{	}};class Solution {    public:	ListNode *removeNthFromEnd(ListNode *head, int n)	{		//Two pointers, where l starts from head and r starts from head+n.		ListNode *l = head;		ListNode *r = head;		ListNode *p;		for (int i = 0; i < n; i++) {			r = r->next;		}		if (r == nullptr) { // n == sz			p = head;			head = head->next;			delete p;			return head;		}		while (r->next != nullptr) {			r = r->next;			l = l->next;		}		p = l->next;		l->next = p->next;		delete p;		return head;	}};

leetcode hot 100 rewrite

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
struct ListNode {        int val;        ListNode *next;        ListNode()                : val(0)                , next(nullptr)        {        }        ListNode(int x)                : val(x)                , next(nullptr)        {        }        ListNode(int x, ListNode *next)                : val(x)                , next(next)        {        }};class Solution {    public:        ListNode *removeNthFromEnd(ListNode *head, int n)        {                ListNode *virtual_head = new ListNode(0, head);                ListNode *p = virtual_head, *q;                int i, nr_node = 0, tpos;                while (p->next != nullptr) {                        p = p->next;                        nr_node++;                }                tpos = nr_node - n;                p = virtual_head;                for (i = 0; i < tpos; i++) {                        p = p->next;                }                // p->next is target                q = p->next;                p->next = q == nullptr ? nullptr : q->next;                head = virtual_head->next;                delete virtual_head;                return head;        }};
Loading comments…