leetcode_[python/C++]_19. Remove Nth Node From End of List(删除链表末第n个节点)

给定一个链表,删除倒数第n个节点并返回修改后的链表头。例如,给定链表1->2->3->4->5和n=2,删除后链表变为1->2->3->5。本文介绍了多种解法,包括使用一个指针加计数、两个指针、二级指针以及递归的方法,并给出了C++和Python的代码实现。
摘要由CSDN通过智能技术生成

题目链接
【题目】
Given a linked list, remove the nth node from the end of list and return its head.

For 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.
Try to do this in one pass.


【分析】
做法(1):一个指针+count len(链表)
做法(2):两个指针
做法(3):两个指针+增加一个pre指针
做法(4):二级指针
做法(5):递归
附上最优runtime
这里写图片描述
这里写图片描述


C++:
一个指针+count len(链表)

/**
 * 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) {
        if( head == NULL ) return NULL;
        ListNode * pre = head;
        int count = 0;
        while( pre != NULL ){
            count ++;
            pre = pre->next;
        }
        int m = count - n - 1;
        int c = 0;
        ListNode * p = head;
        if( m == -1 ) return head->next;
        while( c != m ){
           c ++;
           p = p->next;
        }   
        ListNode *temp = p->next->next;
        if(temp == NULL) p->next = NULL;
        else p->next = temp;
        return head;
    }
};

两个指针+pre指针

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if( head == NULL ) return NULL;
        ListNode * pre = NULL, * current = head, * end = head;
        for(int i = 0 ; i < n ; i ++ ) end = end->next;
        while( end ){
            pre = current;
            current = current->next;
            end = end->next;
        }
        if( pre == NULL ) return head->next;
        else pre->next = current->next;
        return head;

    }
};

链表头增加一个节点:

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        if( head == NULL ) return NULL;
        ListNode * new_head = new ListNode(0);
        new_head->next = head;
        ListNode * current = new_head, * end = new_head;
        for(int i = 0 ; i <= n ; i ++ ) end = end->next;
        while( end ){
            current = current->next;
            end = end->next;
        }
        current->next = current->next->next;
        return new_head->next;

    }
};

二级指针:
参考学习二级指针

class Solution
{
public:
    ListNode* removeNthFromEnd(ListNode* head, int n)
    {
        ListNode** t1 = &head, *t2 = head;//t1 == pre   *t1 = current   (*t1)->next = current->next  
        for(int i = 0; i < n; ++i)
        {
            t2 = t2->next;
        }
        while(t2 != NULL)
        {
            t1 = &((*t1)->next);
            t2 = t2->next;
        }
        *t1 = (*t1)->next;
        return head;
    }
};

递归:

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int& n) {
        ListNode * node = new ListNode(0);
        node->next = head;
        removeNode(node, n);
        return node->next;
    }

    void removeNode(ListNode* head, int& n){
        if(!head) return;
        removeNode(head->next, n);
        n--;
        if(n == -1) {
            head->next = head->next->next; 
        }
        return;
    }
};

python


构造链表:

def removeNthFromEnd(self, head, n):
    self.next, nodelist  = head, [self]
    while head.next:
        if len(nodelist) == n:
            nodelist.pop(0)
        nodelist += head,
        head = head.next
    nodelist[0].next = nodelist[0].next.next 
    return self.next

新建链表:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def removeNthFromEnd(self, head, n):
        collection=list();
        ptr=head;
        collection.append(ptr)
        while ptr.next is not None:
            collection.append(ptr.next)
            ptr=ptr.next
        length=len(collection);
        if length-n==0 and length>1:
            return collection[1]
        elif length-n==0 and length==1:
            return None
        elif n>1:
            collection[length-n-1].next=collection[length-n+1]
            return head
        elif n==1:
            collection[length-2].next=None
            return head

两个指针:

class Solution(object):
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """

        current = end = self
        self.next = head
        while end.next:
            if n:
                n -= 1
            else:
                current = current.next
            end = end.next
        current.next = current.next.next
        return self.next 

两个指针另一种写法:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution(object):
    def removeNthFromEnd(self, head, n):
        current = head
        end = head
        for i in range(0,n):
            end = end.next
        if(end == None):
            return head.next
        while(end.next != None):
            end = end.next
            current = current.next
        current.next = current.next.next
        return head

这个效率比较高

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值