链表
时间复杂度
类型 数组 链表 查找 O(1) O(n) 插入 O(n) O(1) 删除 O(n) O(1)
链表的节点
struct node{
int data;
struct node* nxt;
} ;
typedef struct node Node;
顺序创建链表
Node* createLinkList ( int n) {
Node* head = ( Node* ) malloc ( sizeof ( Node) ) ;
Node* end = ( Node* ) malloc ( sizeof ( Node) ) ;
head = end;
int val = 0 ;
for ( int i = 1 ; i <= n; ++ i) {
Node* crt = ( Node* ) malloc ( sizeof ( Node) ) ;
scanf ( "%d" , & val) ;
crt- > data = val;
end- > nxt = crt;
end = crt;
}
end- > nxt = NULL ;
return head;
}
空间释放
void free_list ( Node* head) {
Node* temp;
do {
temp = head- > nxt;
free ( head) ;
head = temp;
} while ( head- > nxt != NULL ) ;
}
操作
遍历
void print_list ( Node* head) {
while ( head- > nxt != NULL ) {
head = head- > nxt;
printf ( "%d " , head- > data) ;
}
printf ( "\n" ) ;
}
根据索引查找
void query ( Node* head, int n) {
for ( int i = 0 ; i < n; ++ i) {
head = head- > nxt;
}
printf ( "%d\n" , head- > data) ;
}
根据索引修改
void change ( Node* head, int n, int val) {
for ( int i = 0 ; i < n; ++ i) {
head = head-> nxt;
}
head-> data = val;
}
根据索引插入
void insert ( Node* head, int n, int val) {
for ( int i = 0 ; i < n; ++ i) {
head = head-> nxt;
}
Node * temp = ( Node* ) malloc ( sizeof ( Node) ) ;
temp-> data = val;
temp-> nxt = head-> nxt;
head-> nxt = temp;
}
根据索引删除
void delete_node ( Node* head, int n) {
for ( int i = 0 ; i < n - 1 ; ++ i) {
head = head-> nxt;
}
Node * temp = head-> nxt;
head-> nxt = temp-> nxt;
free ( temp) ;
}
合并两个链表
void emerge ( Node* head1, Node* head2) {
while ( head1-> nxt != NULL ) {
head1 = head1-> nxt;
}
head1-> nxt = head2-> nxt;
free ( head2) ;
}
主函数
int main ( ) {
Node* head1 = createLinkList ( 5 ) ;
Node* head2 = createLinkList ( 3 ) ;
print_list ( head1) ;
query ( head1, 5 ) ;
change ( head1, 5 , 30 ) ;
print_list ( head1) ;
insert ( head1, 3 , 6 ) ;
print_list ( head1) ;
delete_node ( head1, 4 ) ;
print_list ( head1) ;
emerge ( head1, head2) ;
print_list ( head1) ;
free_list ( head1) ;
free_list ( head2) ;
free ( head1) , free ( head2) ;
head1 = NULL ;
head2 = NULL ;
}