C语言实现链表

大作业水平...

#include<stdio.h>
#include<stdlib.h>

struct node{
struct node* next;
int c;
};

struct node* init_node(int input)
{
struct node* p;
p = malloc(sizeof(struct node));
p->c = input;
return p;
}

void insert_node(struct node *head, int new)
{
struct node *temp = (struct node*)(malloc(sizeof(struct node)));
// struct node *temp;
while(head->next != NULL)
head = head->next;
head->next = temp;
temp->c = new;
temp->next = NULL;
}

void display_list(struct node* head){
if(head == NULL)
{
printf("error.\n");
return;
}
struct node *p = head;
while(p->next != NULL)
{
printf("%d ",p->c);
p = p->next;
}
printf("%d ", p->c);
printf("NULL\n");
}

void destroy_list(struct node *head)
{
if (NULL != head) {
destroy_list(head->next);
// free(head->c);
free(head);
printf("destroy a list...\n");
}
}

struct node* copy_list(struct node* head)
{
struct node* p = (struct node*)(malloc(sizeof(struct node)));
p->next = NULL;
if(head == NULL)
{
printf("head is NULL.\n");
return;
}
p->c = head->c;
head = head->next;
while(head != NULL)
{
printf("copying... head->c: %d\n", head->c);
insert_node(p, head->c);
head = head->next;
}
// insert_node(p, head->c);
return p;
}

struct node* reverse_list(struct node* head)
{
struct node* p;
struct node* t;
p = (struct node*)(malloc(sizeof(struct node)));
p->c = head->c;
p->next = NULL;
while(head->next != NULL)
{
head = head->next;
t = p;
p = (struct node*)(malloc(sizeof(struct node)));
p->next = t;
p->c = head->c;
}
return p;
}

int main(int argc, char** argv)
{
struct node *head = init_node(1);
long long i;
insert_node(head, 2);
insert_node(head, 3);
insert_node(head, 4);
insert_node(head, 5);
insert_node(head, 6);
insert_node(head, 7);
display_list(head);
struct node* copy = copy_list(head);
printf("copy done.\n");
struct node* reve = reverse_list(head);
display_list(reve);
for (i = 0; i < 0x1000000; i++) reve = reverse_list(head);
display_list(reve);
display_list(copy);
destroy_list(head);
destroy_list(copy);
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值