Question: Remove Nth node from end of list

Given a linked list, remove the n-th node from the end of list and return its head.

Example:

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:

Given n will always be valid.

Method 1
One pass
Time complexity O(n)

/**
 * 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*current=head;
        ListNode*previous;
        int cout=0;
        while(current!=0&&cout<n)
        {
            previous=current;
            current=current->next;
            cout++;
        }
        if(current==0&&cout==1)
        {
            ListNode*DeleteNode=head;
            delete DeleteNode;
            head=NULL;
        }
        else if (current==0)
        {
            ListNode*DeleteNode=head;
            head=head->next;
            delete DeleteNode;
        }
        else
        {
            ListNode*rear=current;
            current=head;
            while(rear!=0)
            {
                rear=rear->next;
                previous=current;
                current=current->next;
            }
            previous->next=current->next;
            delete current;
        }
        return head;
        }
};

leetcode Remove Nth node from end of list C++
Method 2
Two pass
Time complexity O(n)
Explanation:One pass is to determine the number of node, the other is to delete the demanded node!

/**
 * 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) 
    {
        int NodeNumber=0;
        ListNode*current=head;
        while(current!=0)
        {   
            NodeNumber++;
            current=current->next;
         }
        if(NodeNumber==1&&n>=1)
        {
            head=NULL;
        }
        else if(NodeNumber==n)
        {
            ListNode*DeleteNode;
            DeleteNode=head;
            head=head->next;
            delete DeleteNode;
        }
        else
        {   current=head;
            int j=0;
            ListNode*previous;
            current=head;
            for(current;j<NodeNumber-n;previous=current,current=current->next)
            {
                j++;
            }
            previous->next=current->next;
            delete current;
        }
        return head;
    }
};

leetcode Remove Nth node from end of list C++

本程序仅供学习参考之用,如若转载,请注明出处。
如果你对本程序感到满意,可点击关注本博客!!

相关文章:

  • 2022-02-16
  • 2022-02-24
  • 2021-11-15
  • 2022-12-23
  • 2022-12-23
  • 2021-08-02
猜你喜欢
  • 2021-09-07
  • 2021-10-27
  • 2021-11-14
  • 2021-07-11
  • 2022-02-24
  • 2021-09-15
相关资源
相似解决方案