建立链表并升序排列

img

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <bits/stdc++.h>

using namespace std;

struct node{
int elem;
struct node* next;
};

int main ()
{
int n=5,num;
node* head=new node();
head->next=NULL;
while(n--){
cin>>num;
node* p=head->next;
node* q=head;
while(p!=NULL&&p->elem<num){
q=p;
p=p->next;
}
node* s=new node();
s->elem=num;
s->next=p;
q->next=s;
}
//输出链表
node *cur=head->next;
while(cur!=NULL){
cout<<cur->elem<<' ';
cur=cur->next;
}
}

双指针合并链表

尾插法

记得规范写法,创建出的头结点一定要初始化next

​ node* reshead=new node();

​ reshead->next = nullptr; // 初始化next

空指针和野指针

二、空指针(NULL/nullptr)—— “明确的空白地址”

\1. 定义

空指针是主动赋值为 “空” 的指针,代表这个指针当前不指向任何有效的内存空间。

C++11 及以后推荐用 nullptr(真正的指针类型);

旧写法用 NULL(本质是宏定义,等价于整数 0)。

\2. 通俗比喻

就像你手里有一张空白的地址纸条,上面明确写着 “无地址”—— 你知道这个指针没有可访问的内存,不会乱找。

三、野指针(迷途指针)—— “无效的随机地址”

\1. 定义

野指针是未初始化 / 指向已释放内存 / 越界 的指针,指针本身非空,但指向的内存区域是非法的(要么不存在,要么不属于当前程序)。

\2. 通俗比喻

就像你手里的地址纸条写着一个:

不存在的门牌号(指针未初始化);

已经被拆掉的房子地址(指向已释放的内存);

别人家里的门牌号(指针越界);

你按这个地址找过去,要么找不到(崩溃),要么闯到别人家里(修改了不该改的数据)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <bits/stdc++.h>

using namespace std;

struct node{
int elem;
node* next;
};

//尾插法创建有序链表
node* create(int ssize){
node* head=new node();
head->next = nullptr; // 头节点next初始化
node* tail=head;
int num;
for(int i=0;i<ssize;i++){
cin>>num;
node* n=new node();
n->elem=num;
n->next = nullptr; // 关键修复:初始化next,避免野指针
tail->next=n;
tail=n;
}
return head;
}

//双指针合并链表
node* mer(node* head1,node* head2){
node* reshead=new node();
reshead->next = nullptr; // 初始化next
node* restail=reshead;
node*p1=head1->next;
node* p2=head2->next;
while(p1!=NULL&&p2!=NULL){
if(p1->elem < p2->elem){
restail->next=p1;
p1=p1->next;
}
else{
restail->next=p2;
p2=p2->next;
}
restail=restail->next;
}
if(p1!=NULL){
restail->next=p1;
}
if(p2!=NULL){
restail->next=p2;
}
return reshead;
}

int main ()
{
int s1,s2;
cin>>s1;
node*head1=create(s1);
cin>>s2;
node *head2=create(s2);
node* result=mer(head1,head2);
node* a=new node();
a=result->next;
while(a!=NULL){
cout<<a->elem<<' ';
a=a->next;
}
return 0;
}

递归法反转链表(感觉不重要)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 递归法反转链表(有效节点的头指针,非哨兵头)
node* reverseRecursive(node* cur) {
// 终止条件:空节点 或 最后一个节点
if (cur == nullptr || cur->next == nullptr) {
return cur;
}
// 递归到最后一个节点,返回反转后的头节点(last)
node* last = reverseRecursive(cur->next);
// 让后一个节点指向当前节点(反转)
cur->next->next = cur;
// 当前节点的next置空(避免循环)
cur->next = nullptr;
// 逐层返回反转后的头节点
return last;
}