节点、链表结构
链表操作:增删改查
#include <stdio.h>
#include <stdlib.h>
/*结构体*/
typedef int data_t;
typedef struct node{
data_t data;
struct node *next;
}listnode, *linklist;
/*声明函数*/
linklist list_create();
int list_tail_insert(linklist H, data_t value);
int list_insert(linklist H, data_t value, int pos);
int list_delete(linklist H, int pos);
linklist list_get(linklist H, data_t value, int pos);
int list_show(linklist H);
linklist list_free(linklist H);
/*创建链表*/
linklist list_create(){
linklist H;
H = (linklist)malloc(sizeof(listnode));
if(H == NULL){
printf("malloc failed\n");
return H;
}
H->data = 0;
H->next = NULL;
return H;
}
/*链表尾部插入*/
int list_tail_insert(linklist H, data_t value){
linklist p, q;
if(H == NULL){
printf("H is NULL\n");
return -1;
}
//create new node p
p = (linklist)malloc(sizeof(listnode));
if(p == NULL){
printf("malloc failed\n");
return -1;
}
p->data = value;
p->next = NULL;
//locate tail node
q = H;
while(q->next != NULL){
q = q->next;
}
//insert
q->next = p;
return 0;
}
/*在链表pos处插入value*/
int list_insert(linklist H, data_t value, int pos){
linklist p, q;
if(H == NULL){
printf("H is NULL\n");
return -1;
}
//create new node p
p = (linklist)malloc(sizeof(listnode));
if(p == NULL){
printf("malloc failed\n");
return -1;
}
p->data = value;
p->next = NULL;
//locate node q (pos-1)
q = list_get(H, pos-1);
if(q == NULL){
return -1;
}
//insert
q->next = p->next;
p->next = q;
return 0;
}
/*删除pos处节点*/
int list_delete(linklist H, int pos){
linklist p, q;
if(H == NULL){
printf("H is NULL\n");
return -1;
}
//locate prior (pos-1)
p = list_get(H, pos-1);
if(p == NULL){
return -1;
}
if(p->next == NULL){
printf("delete pos is invalid\n");
return -1;
}
//update list
q = p->next;
p->next = q->next;
//free q
printf("free:%d\n",q->data);
free(q);
q = NULL;
return 0;
}
/*查询pos处的节点*/
linklist list_get(linklist H, int pos){
linklist p;
int i;
if(H == NULL){
printf("H is NULL\n");
return NULL;
}
if(pos == -1){
return H;
}
if(pos < -1){
printf("pos is invalid\n");
}
p = H;
i = -1;
while(i < pos){
p = p->next;
if(p == NULL){
printf("pos is invalid\n");
return NULL;
}
i++;
}
return p;
}
/*遍历链表*/
int list_show(linklist H){
linklist p;
if(H == NULL){
printf("H is NULL\n");
return NULL;
}
p = H;
while(p->next != NULL){
printf("%d ",p->next->data);
p = p->next;
}
return 0;
}
/*删除整个链表*/
linklist list_free(linklist H){
linklist p;
if(H == NULL){
printf("H is NULL\n");
return NULL;
}
printf("free:");
while(H != NULL){
p = H;
printf("%d ",p->data);
free(p);
H = H->next;
}
puts("");
return NULL;
}