LeetCode-019-Remove Nth Node Fro

2019-07-22  本文已影响0人  Hanielxx

Problem

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

Note:
Given n will always be valid.

Examples:

Input:1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.

Solutions

第一种方法是两次遍历,第一次计算出一共多少个节点,然后算出应该向后移动多少次,
找到那个节点, 删掉

C++ Codes

双指针

/**
 * 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* p = head;
        ListNode* pre=head;
        for(n;n>=1;n--) p=p->next;
        if(p==NULL)return head->next;
        while(p->next!=NULL){
            p=p->next;
            pre=pre->next;
        }
        pre->next=pre->next->next;
        return head;
    }
};

Python Codes

class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        if not head:return 
        dummy = ListNode(0)
        dummy.next = head
        fast = dummy
        while n:
            fast = fast.next
            n -= 1
        slow = dummy
        while fast and fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return dummy.next

总结


上一篇 下一篇

猜你喜欢

热点阅读