- 将两个递增的有序链表合并为一个递增的有序链表。要求结果链表仍使用原来两个链表的存储空间, 不另外占用其它的存储空间。表中不允许有重复的数据。
#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;
}
- 设计一个算法,通过遍历一趟,将链表中所有结点的链接方向逆转,仍利用原表的存储空间。
#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;
}