这里介绍链表的打印输出,链表的反向和链表销毁。
1)正向打印出所有的节点:
int print_lst(list *head)
{
if (head == NULL)
{
perror("head is null !\n");
return -1;
}
list *p;
int count;
for(p = head, count = 0; p != NULL; ++ count)
{
if (count != 0 && (count % 5) == 0)
printf("\n");
printf ("%d\t", *((int *)(p->p_data)));
p = p->next;
}
printf("\n");
return 0;
}
2)反向打印所有的结点:
int print_lst_from_tail(list *head)
{
printf("print out the list from tail!\n");
if (head == NULL)
{
perror(" head is null !\n");
return -1;
}
list *p, *tail;
int count;
for (p = head; p->next != NULL; p = p->next)
;
tail = p;
for(p = tail, count = 0; p != NULL; ++ count)
{
if (count != 0 && (count % 5) == 0)
printf("\n");
printf ("%d\t", *((int *)(p->p_data)));
p = p->pre;
}
printf("\n");
return 0;
}
3)对链表所有的元素反向:
int reverse_lst(list **hd)
{
printf("%s!\n", __func__);
list *head = *hd;
if (head == NULL)
{
perror("invalid list!\n");
return -1;
}
list *p, *q, *r, *tail;
for (r = head; r->next != NULL; r = r->next)
;
tail = r;
for (p = tail; p != NULL; )
{
q = p;
p = p->pre;
r->next = q;
q->pre = r;
q->next = NULL;
r = q;
}
tail->pre = NULL;
*hd = tail;
return 0;
}
4)销毁:
int free_lst(list *lst)
{
if (lst == NULL)
return -1;
list *p, *q;
for (p = lst; p->next != NULL; )
{
q = p;
if (p->next != NULL)
{
if (q->p_data != NULL)
free(q->p_data);
free(q);
p = p->next;
}
else
{
if (p->p_data != NULL)
free (p->p_data);
free(p);
}
}
return 0;
}
下一篇介绍链表的冒泡排序。