提升代码能力第四天

Leetcode-19

在这里插入图片描述
在这里插入图片描述
最普通的思路就是两次遍历链表,第一次遍历找出链表的长度和所要删除节点为第几个,第二次遍历时删除该节点

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode*prehead=new ListNode(0);
        ListNode*cur=prehead;
        ListNode*list=head;
        int sum=0;
        while(list){//计算链表总共多少节点
            sum++;
            list=list->next;
        }
        int index=sum-n+1;//计算链表的第几个节点为要删去的
        int count=1;
        cur->next=head;
        while(count<index){
            
            cur=cur->next;
            count++;
        }
        ListNode*ind=cur->next;//ind以所要删除节点为头指针
        cur->next=ind->next;

        return prehead->next;
    }
    
};

只遍历一次的做法: 利用两个指针同时移动,让使得遍历一次结束其中的一个指针正好指向倒数n个位置
first和second指针首先同时指向添加哑节点之后的链表,first向前移动n+1步,二者之间间隔n个节点,同时移动,当first指向末尾(为末尾节点指向null)的null时,second刚好指向链表倒数第n个节点
注意哑节点null
在这里插入图片描述

class Solution {
public:
    ListNode* removeNthFromEnd(ListNode* head, int n) {
        ListNode*prehead=new ListNode(0);
        prehead->next=head;
        ListNode*first=prehead;
        ListNode*second=prehead;
        int i=0;
        while(i<n+1){//计算链表总共多少节点
            i++;
            first=first->next;
        }
        while(first){
            first=first->next;
            second=second->next;
        }
        second->next=second->next->next;

        return prehead->next;
    }
    
};
发布了4 篇原创文章 · 获赞 0 · 访问量 72

猜你喜欢

转载自blog.csdn.net/Sophia2333333331/article/details/105423376