[LeetCode]019-Remove Nth Node From End of List

题目:
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.

Solution(1):
思路,找到这个点的前节点和后节点,连接起来。

ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode* temp = head; 
        int num = 0;
        while(temp != NULL)
        {
            temp = temp->next;
            num++;
        }
        int pre_num = num - n-1;
        int del_num = num - n;

        ListNode*  pre_node = head;
        ListNode* del_node =head;
        if(n == num)
        {
            head = head->next;

            return head;
        }

        while(pre_num--)
        {
            pre_node = pre_node->next;
        }
        while(del_num--)
        {
            del_node = del_node->next;
        }
        pre_node->next = del_node->next;
        delete[] del_node;

        return head;
    }

Solution(2):
思路:定义双指针,保持距离为n,然后一个移到最后,另一个自然就是要删除节点的前一个节点了。

ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        if(head == NULL || head->next == NULL)
            return NULL;
        ListNode * first_node = head;
        ListNode *second_node = head;
        for(int i=0;i<n;i++)
            first_node = first_node->next;
        if(first_node == NULL)//delete the head node
        {
            head = head->next;
            return head;
        }
        while(first_node->next !=NULL)
        {
            first_node = first_node->next;
            second_node = second_node->next;
        }
        second_node->next = second_node->next->next;
        return head;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值