#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list *next;
};
//建立链表节点
struct list *create_list()
{
return calloc(sizeof(struct list),1);
}
//往链表的第n个节点插入新节点
struct list *insert_list(struct list *ls,int n,int data)
{
struct list *p = ls;
while(p && n--)
{
p = p->next;
}
if(NULL == p)
{
return NULL;
}
struct list *node = create_list();
node->data = data;
node->next = p->next;
p->next = node;
return node;
}
//删除第n个节点
int delete_list(struct list *ls,int n)
{
struct list *p = ls;
while(p && n--)
{
p = p->next;
}
if(NULL == p)
{
return -1;
}
struct list *temp = p->next;
p->next = temp->next;
free(temp);
return 0;
}
//删除链表只留头节点
void clear_list(struct list *ls)
{
struct list *p = ls->next;
while(p)
{
struct list *tmp = p->next;
free(p);
p = tmp;
}
ls->next = NULL;
}
//判断链表是否为空
int empty_list(struct list *ls)
{
if(ls->next)
{
return 0;
}
else
{
return -1;
}
}
//定位第n个节点
struct list *locale_list(struct list *ls,int n)
{
struct list *p = ls;
while(p && n--)
{
p = p->next;
}
if(p == NULL)
{
return NULL;
}
return p;
}
//查找值为data的节点
struct list *elem_list(struct list *ls,int data)
{
struct list *p = ls;
while(p)
{
if(p->data == data)
return p;
p = p->next;
}
return NULL;
}
//查找值为data节点的下标
int elem_pos(struct list *ls,int data)
{
int index = 0;
struct list *p = ls;
while(p)
{
index++;
if(p->data == data)
return index;
p = p->next;
}
return -1;
}
//统计链表长度
int count_list(struct list *ls)
{
struct list *p = ls;
int count = 0;
while(p)
{
count++;
p = p->next;
}
return count;
}
//返回链表最后一个节点
struct list *last_list(struct list *ls)
{
struct list *p = ls;
while(p->next)
{
p = p->next;
}
return p;
}
//合并两个节点
void merge_list(struct list *ls1,struct list *ls2)
{
last_list(ls1)->next = ls2->next;
}
//遍历打印整个链表
void traverse(struct list *ls)
{
struct list *p = ls;
while(p)
{
printf("%d\n",p->data);
p = p->next;
}
}
int main()
{
struct list *first = create_list();
struct list *second = create_list();
struct list *third = create_list();
first->next = second;
second->next = third;
third->next = NULL;
first->data = 1;
second->data = 2;
third->data = 3;
insert_list(first,1,10);
insert_list(first,1,20);
insert_list(first,1,30);
delete_list(first,2);
//clear_list(first);
traverse(first);
printf("count = %d\n",count_list(first));
printf("data = %d\n",locale_list(first,3)->data);
printf("last data = %d\n",last_list(first)->data);
struct list *first1 = create_list();
int i;
for(i = 0; i < 10; i++)
{
insert_list(first1,0,i);
}
merge_list(first,first1);
traverse(first);
return 0;
}