-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathch02-LinkList.cpp
125 lines (121 loc) · 2.27 KB
/
ch02-LinkList.cpp
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
//
// Created by zsf on 2021/6/20.
//
#include "iostream"
using namespace std;
typedef struct LNode{
int data;
LNode *next;
}LNode,*LinkList;
bool InitList(LinkList &L){
//L=(LNode *)malloc(sizeof(LNode));
L=new LNode;
if(L==NULL)
return false;
L->next=NULL;
return true;
}
LinkList List_HeadInsert(LinkList &L){//头插法
int e;
scanf("%d",&e);
while (e!=-1){
LNode *s=new LNode;
s->data=e;
s->next=NULL;
s->next=L->next;
L->next=s;
scanf("%d",&e);
}
return L;
}
LinkList List_TailInsert(LinkList &L){//尾插法
int e;
LNode *r=L;
scanf("%d",&e);
while (e!=-1){
LNode *s=new LNode;
s->data=e;
s->next=NULL;
r->next=s;
r=s;
scanf("%d",&e);
}
return L;
}
LNode *GetElem(LinkList &L,int i){//按位查找
if(i<0)return NULL;
LNode *p=L->next;
if(i==0)return p;
int j=1;
while (p && j<i){
p=p->next;
j++;
}
return p;
}
LNode *LocateElem(LinkList &L,int e){//按值查找
LNode *p=L->next;
while (p && p->data!=e){
p=p->next;
}
return p;
}
int Length(LinkList &L){
LNode *p=L;
int len=0;
while (p->next){
len++;
p=p->next;
}
return len;
}
void print(LinkList &L){
LNode *p=L->next;
while (p!=NULL){
printf("%d ",p->data);
p=p->next;
}
}
bool ListInsert(LinkList &L,int i,int e){//按位置插入结点
LNode *p=GetElem(L,i-1);
if(p==NULL){
return false;
}
else{
LNode *s=new LNode;
s->data=e;
s->next=p->next;
p->next=s;
return true;
}
}
bool ListDelete(LinkList & L,int i,int &e){
LNode *p=GetElem(L,i-1);
if(p==NULL)
return false;
else{
LNode *q=p->next;
p->next=q->next;
e=q->data;
delete(q);
return true;
}
}
int main(){
LinkList L;
int e;
InitList(L);
//List_HeadInsert(L);
List_TailInsert(L);
// ListInsert(L,2,99);
ListDelete(L,2,e);
print(L);
// if(GetElem(L,2)){
// printf("%d ",GetElem(L,2)->data);
// }
// if(LocateElem(L,2)){
// printf("%d ",LocateElem(L,2)->data);
// }
// printf("%d",Length(L));
return 0;
}