#include <stdio.h>
#include <stdlib.h>
#define ERROR -1
#define SUCCESS 0
struct list_node
{
int data;
struct list_node *next;
/* data */
};
typedef struct list_node link_list;
int list_get_size(link_list *list)
{
int count = 0;
link_list *p = list;
if(!list)
{
return ERROR;
}
while(p->next)
{
count++;
p = p->next;
}
return count;
}
int list_insert_head(link_list *list, int data)
{
struct list_node *new = (struct list_node *)malloc(sizeof(struct list_node *));
new->data = data;
link_list *p = list;
while(new->data!=-1)
{
new->next = p->next;
p->next = new;
break;
}
return SUCCESS;
}
int list_insert_tail(link_list *list, int data[], int len)
{
link_list *r = list;
for(int i = 0; i <len; i++)
{
struct list_node *new = (struct list_node *)malloc(sizeof(struct list_node *));
new->data = data[i];
r->next = new;
r = new;
}
r->next = NULL;
return ERROR;
}
struct list_node* list_reverse( struct list_node *list)
{
struct list_node *new_head = NULL;
while(list)
{
struct list_node *new_node = (struct list_node *)malloc(sizeof(struct list_node));
new_node->data = list->data;
new_node->next = new_head;
new_head = new_node;
list = list->next;
}
return new_head;
}
int reverse(link_list *list)
{
int i = 0;
struct list_node *p = list;
while (p->next)
{
p = p->next;
printf("%d\n", list_reverse(p)->data);
}
return 0;
}
int list_print(link_list *list)
{
int i =0;
struct list_node *p = list;
while(p->next)
{
p = p->next;
printf("%d:%d\n", i++, p->data);
}
return 0;
}
int main(int argc, char const *argv[])
{
link_list list;
link_list list1;
int i =0;
int data[10] = {1,2,3,4,5,6,7,8,9,0};
printf("头插法: \n");
for(int i = 0; i <10; i++)
{
list_insert_head(&list, data[i]);
}
list_print(&list);
printf("list len =%d\n", list_get_size(&list));
printf("尾插法:\n");
for (int i = 0; i < 10; i++)
{
list_insert_tail(&list1, data, 10);
}
list_print(&list1);
printf("链表翻转:\n");
reverse(&list1);
return 0;
}
标签:node,单链,语言,int,list,next,new,struct
From: https://www.cnblogs.com/zhaodejin/p/17922406.html