c语言实现:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
struct Node
{
int data;
struct Node* next;
}node,*p;
struct Node* init_node()
{
struct Node *head = (struct Node*)malloc(sizeof(struct Node));
head->next = NULL;
return head;
}
void head_insert(int date,struct Node *head)
{
struct Node *p1 = (struct Node*)malloc(sizeof(struct Node));
if(p1 == NULL)
{
perror("malloc error");
}
p1->data = date;
p1->next = head->next;
head->next = p1;
};
//反转链表
void revert_head(struct Node* head)
{
struct Node *pre= head;
struct Node *cur = head->next;
struct Node *after;
while(cur->next != NULL )
{
after = cur->next;
cur->next = pre;
pre = cur;
cur = after;
}
cur->next = pre;
head->next->next = NULL;
head->next = cur;
}
//打印链表
void printf_head(struct Node* head)
{
struct Node* temp = head;
while(temp->next != NULL)
{
temp = temp->next;
printf("the date id %d\n",temp->data);
}
}
//销毁链表
void delete_head(struct Node* head)
{
struct Node* temp = head;
while(temp->next != NULL)
{
temp = temp->next;
printf("the date id %d\n",temp->data);
free(temp);
}
free(head);
}
int main()
{
struct Node *head = init_node();
int num = 4;
for(int i = 4;i > 0;i--)
{
head_insert(i,head);
}
//head_insert(num,head);
printf_head(head);
printf("revert \n");
revert_head(head);
printf_head(head);
return 0;
}
|