(数据结构期末复习)合并两个有序链表、将链表原地翻转

  1. 将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍使用原来两个链表的存储空间, 不另外占用其它的存储空间。表中不允许有重复的数据。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct Node{
    int val;
    Node* next;
};

void insert(Node* &h,int val){
    Node* tmp = new Node;
    tmp->val = val;
    tmp ->next = h;
    h = tmp;
}

void print(Node* h){
    while(h){
        cout << h->val << " ";
        h = h->next;
    }
    cout << endl;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    Node* h1 = new Node;
    Node* h2 = new Node;
    h1->val = 100;
    h2->val = 90;
    h1 ->next = NULL;
    h2->next = NULL;
    insert(h1,80);
    insert(h1,70);
    insert(h1,60);
    insert(h1,40);
    insert(h1,20);
    insert(h1,10);
    insert(h1,1);
    insert(h2,89);
    insert(h2,79);
    insert(h2,63);
    insert(h2,62);
    insert(h2,61);
    insert(h2,9);
    print(h1);
    print(h2);
    Node* r,*n1,*n2,*t;
    if(h1->val < h2->val){
        r = h1;
        n1 = h1->next;
        n2 = h2;
    }else{
        r = h2;
        n1 = h1;
        n2 = h2->next;
    }
    t = r;
    while(n1 && n2){
        if(n1->val < n2->val){
            t->next = n1;
            t = n1;
            n1 = n1->next;
        }else{
            t->next = n2;
            t = n2;
            n2 = n2->next;
        }
    }
    if(n1){
        t->next = n1;
    }else{
        t->next = n2;
    }
    print(r);
	return 0;
}

  1. 设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

struct Node{
    int val;
    Node* next;
};

void insert(Node* &h,int val){
    Node* tmp = new Node;
    tmp->val = val;
    tmp ->next = h;
    h = tmp;
}

void print(Node* h){
    while(h){
        cout << h->val << " ";
        h = h->next;
    }
    cout << endl;
}

int main() {
	ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
    Node* h = new Node;
    h->val = 2048;
    h ->next = NULL;
    insert(h,1024);
    insert(h,512);
    insert(h,256);
    insert(h,128);
    insert(h,64);
    insert(h,32);
    insert(h,16);
    insert(h,8);
    insert(h,4);
    insert(h,2);
    insert(h,1);
    insert(h,0);
    insert(h,-1);
    print(h);
    Node* p,*n,*t;
    p = NULL;
    n = h;
    while(n){
        t = n->next;
        n->next = p;
        p = n;
        n = t;
    }
    print(p);
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值