ACM模式练习2-链表

DAY 6

48.从单向链表中删除指定值的节点

#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;

struct ListNode{
    int val;
    ListNode* next;
    ListNode():val(0),next(nullptr){}
    ListNode(int x):val(x),next(nullptr){}
    ListNode(int x,ListNode* next):val(x),next(next){}
};

int main() {
    int n,val;
    while(cin>>n){
        cin>>val;
        //由于要删除节点,所以要设置一个虚拟头节点
        auto* dummy_head=new ListNode(-1);
        auto* head=new ListNode(val);
        dummy_head->next=head;//让虚拟头节点指向真实头节点
        vector<int> nums(2*n-2,-1);
        for(int & num : nums){
            cin>>num;
        }
        int deleteNum;
        cin>>deleteNum;
        //输入部分完毕
        for(int i=0;i<nums.size();i+=2){
            auto* node=new ListNode(nums[i]);
            auto* cur=dummy_head;
            while(cur->val!=nums[i+1]){
                cur=cur->next;
            }
            //此时cur指向要被插入的节点
            //此时进行判断,如果是最后的一个节点,直接插即可;
            if(cur->next==nullptr)  cur->next=node;
            else{
                //先把cur->next存下来
                ListNode* temp=cur->next;
                cur->next=node;
                node->next=temp;
            }
        }
        //再让cur指向虚拟头节点,因为要删除节点,所以有个虚拟头节点方便点
        auto* cur=dummy_head;
        while(cur->next->val!=deleteNum){
            cur=cur->next;
        }
        cur->next=cur->next->next;
        cur=head;
        while(cur!=nullptr){
            cout<<cur->val<<" ";
            cur=cur->next;
        }
    }
}

51.输出单向链表中倒数第k个结点

ACM模式的构造链表

方法的话双指针,快的先走k步;直到快的为空的时候,慢指针指向倒数第k个节点。

#include <iostream>
using namespace std;

struct ListNode{
    int val;
    ListNode* next;
    ListNode():val(0),next(nullptr){}
    ListNode(int x):val(x),next(nullptr){}
    ListNode(int x,ListNode* next):val(x),next(next){}
};
int nodeVal(ListNode* node,int k){
    ListNode* fast=node;
    ListNode* slow=node;
    for(int i=0;i<k;i++){
        fast=fast->next;//fast先走k步
    }
    while(fast!=nullptr){
        fast=fast->next;
        slow=slow->next;
    }
    return slow->val;
}

int main() {
    int count_node;
    int val;
    int k;
    while(cin>>count_node){
        auto* head=new ListNode(-1);
        ListNode* p=head;
        for(int i=1;i<=count_node;i++){
            cin>>val;
            auto* tmp=new ListNode(val);
            p->next=tmp;
            p=tmp;
        }
        cin>>k;
        int res=0;
        if(k>=1)    res=nodeVal(head->next,k);
        cout<<res<<endl;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值