LeetCode 19. Remove Nth Node From End of List 对撞指针

19.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.

题意

给定一个链表,移除倒数第n个元素

注意

当给定的n超过链表的长度,n为负数。保证n的合法性
n的计数从0开始还是1开始,该题是从1开始

思路

  1. 这题的重点是倒数第n个元素的定为,从最后往前数等于n的位置是需要删除的
    2.删除一个元素就要知道该元素的前一个元素。
    3.当给定两个指针(start,end),区间内含有n个元素,当end指向NULL链表结尾,start指向元素的下一个元素就是倒数第n个元素,需要删除。
    这里写图片描述

代码

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode *virtualNode = new ListNode(0);
        virtualNode->next = head;
        ListNode *start = virtualNode;
        ListNode *end = virtualNode;

        n+=1;
        while(n--)   //区间[start,end]的元素个数很重要,区间内含所有n个元素
        {
            end=end->next;
        }

        while(end!=NULL)
        {
            start = start->next;
            end = end->next;
        }

        //取next的时候需要知道是否有效
        if(start)
        {
            ListNode *dele = start->next;
            if(dele)
            {
                start->next = dele->next;
                delete dele;
            }
        }

        return virtualNode->next;
    }
};

结果

这里写图片描述

237. Delete Node in a Linked List

题目

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

题意

写一个函数,删除给定的结点

注意

注意这里并没有给链表的头结点,仅仅只给了需要删除的结点
尽管之前说不能给链表的结点赋值,但是这个题需要这样做

思路

给了删除的节点,删除结点之后的信息我们可以知道的。
将删除结点的下一个结点的值赋给删除结点的位置,并将删除结点的next域指向next的next。

代码

class Solution {
public:
    void deleteNode(ListNode* node) {
        //对结点的有效性进行判断
        if(node == NULL)
        {
            return;
        }        
        if(node->next == NULL)
        {
            node = NULL;
            return;
        }        
        node->val = node->next->val;
        ListNode* dele = node->next;
        node->next = dele->next;
        delete dele;

    }
};

结果

效率尽管底,进行了容错处理,真正删除内存
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值