定义
链式存储结构
特点
通过链指针来表示数据元素之间的逻辑关系,而非顺序存储结构
插入,删除方便。容易扩充表容量。
数据结构
typedef struct node
{
int data;
struct node *next;
}linklist;
基本运算
使用带头结点的单链表
// creat linklist
linklist *creat_linklist(void)
{
linklist *head;
linklist *p, *q;
int x;
head = (linklist *)malloc(sizeof(linklist));
head->next = NULL;
q = head;
while(1)
{
scanf("%d", &x);
if(x == 0)
{
break;
}
p = (linklist *)malloc(sizeof(linklist));
p->data = x;
p->next = NULL;
q->next = p;
q = q->next;
}
printf("create linklist ok!\n");
return head;
}
//get linklist length
int get_linklist_length(linklist *h)
{
linklist *tmp = h;
int len = 0;
assert(NULL != h);
while(h->next != NULL)
{
len++;
tmp = tmp->next;
}
return len;
}
//find elem x
linklist *find_elem_from_linklist(linklist *h, int x)
{
linklist *tmp = NULL;
assert(NULL != h);
tmp = h->next;
while(tmp != NULL && tmp->data != x)
{
tmp = tmp->next;
}
return tmp;
}
//insert x at pos of linklist
int insert_elem_in_linklist(linklist *h, int x, int pos)
{
linklist *tmp = NULL;
assert(NULL != h);
tmp = h->next;
for(int i = 1; i < pos-1; i++)
{
tmp = tmp->next;
}
p = (linklist *)malloc(sizeof(linklist));
p->data = x;
p->next = tmp->next;
tmp->next = p;
return RET_SUCCESS;
}
// delete elem x
int delete_elem_linklist(linklist *h, int x)
{
linklist *tmp = NULL;
linklist *p = NULL;
BOOL flag = FALSE;
assert(NULL != h);
p = h;
while(p->next != NULL)
{
tmp = p->next;
if(tmp->data == x)
{
flag = TRUE;
p = p->next;
free(tmp);
}
p = p->next;
}
return flag;
}
// reverse linklist
int reverse_linklist(linklist *h)
{
linklist *p,*q;
p = h->next;
h->next = NULL;
while(p != NULL)
{
q = p
p = p->next;
q->next = h->next;
h->next = p;
}
}
单链表翻转示意图