目录
各个链表的功能函数介绍
1.链表的创建
链表的创建分为两种:一种是链表的顺序就是数据输入的顺序,一种是链表的顺序是经过排序后的顺序。
链表的顺序就是数据输入的顺序:
node *create_list(void)
{
node *head, *p, *q;
int i;
printf("please input data:\n");
head = (node*)malloc(sizeof(node));
scanf("%d", &i);
head->data = i;
p = head;
while (1)
{
scanf("%d", &i);
if (0 == i)
{
p->next = NULL;
return head;
}
q = (node*)malloc(sizeof(node));
q->data = i;
p->next = q;
p = p->next;
}
}
链表的顺序是经过排序后的顺序:
node *create_list1(void)
{
node *new_node, *p = NULL, *cur, *head = NULL;
int data;
while (1)
{
scanf("%d", &data);
if (0 == data)
{
break;
}
new_node = (node*)malloc(sizeof(node));
new_node->data = data;
new_node->next = NULL;
if (NULL == head)
{
head = new_node;
continue;
}
if (new_node->data < head->data)
{
new_node->next = head;
head = new_node;
continue;
}
cur = head;
while ((new_node->data > cur->data)&(cur->next != NULL))
{
p = cur;
cur = cur->next;
}
if (new_node->data > cur->data)
{
cur->next = new_node;
}
else{
p->next = new_node;
new_node->next = cur;
}
}
return head;
}
2.链表的打印
void print_list(node *head)
{
node *p;
p = head;
if (NULL == head)
{
printf("this is empty list\n");
return;
}
printf("list: %d", p->data);
while (p->next != NULL)
{
p = p->next;
printf(" %d", p->data);
}
printf("\n");
}
3.获取链表的长度
int get_list_length(node *head)
{
int i = 0;
node *p;
if (NULL == head)
{
printf("this is empty list\n");
return 0;
}
i = 1;
p = head;
while (p->next != NULL)
{
i++;
p = p->next;
}
return i;
}
4.在链表中插入一个节点
这里的插入是根据插入的位置,插入的。
node *insert_list(node *head, int pos, int data)
{
node *p, *q;
int i = 0;
if (NULL == head)
{
printf("this is empty list\n");
return NULL;
}
p = head;
q = (node *)malloc(sizeof(node));
q->data = data;
if (0 == pos)//insert before the head of the linked list
{
q->next = p;
return q;
}
while (p != NULL)
{
i++;
if (i == pos)
{
q->next = p->next;
p->next = q;
return head;
}
p = p->next;
}
printf("this list hasn't pos\n");
return NULL;
}
5. 寻找链表中的节点
根据需要寻找的节点位置,返回相应的节点地址。
node *search_list(node *head, int pos)
{
node *p;
int i &