typedef struct node
{
int value;
struct node *next;
}node_t;
//创建单链表
node_t *CreateList(int length,int *values)
{
int i;
node_t *head = (node_t *)malloc(sizeof(node_t)); // create list head
node_t *cur = head; //cur始终指向尾节点,开始时指向头节点
node_t *new_node = NULL;
for(i=0;i<length;i++)
{
new_node = (node_t *)malloc(sizeof(node_t));
new_node->value = values[i];
cur->next = new_node;
cur = new_node;
}
cur->next = NULL;
return head;
}
//输出单链表
void PrintList(const node_t *list)
{
node_t *p = list->next;
printf("list values : ");
while(p)
{
printf(" %d",p->value);
p = p->next;
}
printf("\n");
}
//合并两个有序单链表
node_t *MergeList(node_t *list1,node_t *list2)
{
if(list1 == NULL)
return list2;
if(list2 == NULL)
return list1;
node_t *list = (node_t *)malloc(sizeof(node_t)); //创建新链表的表头
node_t *cur = NULL;
list1 = list1->next;
list2 = list2->next;
if(list1->value < list2->value)
{
list->next = list1;
list1 = list1->next;
}
else
{
list->next = list2;
list2 = list2->next;
}
cur = list->next; //cur始终指向新链表的表头,开始指向表头的next
while(list1 && list2)
{
if(list1->value < list2->value)
{
cur->next = list1;
cur = cur->next;
list1 = list1->next;
}
else
{
cur->next = list2;
cur = cur->next;
list2 = list2->next;
}
}
cur->next = (NULL == list1)?list2:list1;
return list;
}
//销毁单链表
void DistroyList(node_t *list)
{
if (list == NULL)
return ;
node_t *p = list;
node_t *cur = p->next;
while(cur)
{
free(p);
p->next = NULL; //将p及p->next指向NULL
p = NULL;
p = cur;
cur = p->next;
}
free(p);//此时cur为NULL,p指向尾节点
p->next = NULL;
p = NULL;
}
//求单链表的长度
int ListLength(node_t *list)
{
int length = 0;
node_t *cur = list->next;
while(cur)
{
length++;
cur = cur->next;
}
return length;
}
//向单链表中插入值
int ListInsert(node_t *list,int value) //将value插入到list的相应的位置,list为一从小到大的有序表
{
node_t *cur = list; //cur始终指向链表的末尾,最开始指向表头
node_t *temp = (node_t *)malloc(sizeof(node_t));
temp->value = value;
temp->next = NULL;
while(cur->next)
{
if((cur->next)->value >= value)
{
temp->next = cur->next;
cur->next = temp;
return 0;
}
cur = cur->next;
}
cur->next = temp; //该值为最大值,插入到链表的最末尾
return 0;
}
//向单链表中删除某节点
int ListDelete(node_t *list,int i) //删除list的第i个节点
{
int j = 0;
node_t *cur = list;
node_t *temp = NULL;
while(j<i-1 && cur) //找到第i-1个节点
{
j++;
cur = cur->next;
}
if(cur)
{
temp = cur->next; //temp指向要删除的节点
if(temp)
{
cur->next = temp->next;
free(temp);
temp->next = NULL;
temp = NULL;
return 0;
}
}
return -1;
}
单链表的部分操作
最新推荐文章于 2024-07-25 19:26:22 发布