反转单链表
头插法逆序,尾插法顺序
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
/*产生随机链表*/
node *creatnode(int n){
srand(time(NULL));
node *head=(node *)malloc(sizeof(node));
head->next=NULL;
for(int i=0;i<n;i++){
node *p=(node *)malloc(sizeof(node));
p->data=rand()%20; /*头插法*/
p->next=head->next;
head->next=p;
}
return head;
}
/*反转链表*/
node *reserve(node *head){
node *new_head=(node *)malloc(sizeof(node));
new_head->next=NULL;
while(head->next!=NULL){
head=head->next;
node *p=(node *)malloc(sizeof(node));
p->data=head->data;
p->next=new_head->next;
new_head->next=p;
}
return new_head;
}
/*打印链表*/
void print(node *head){
while(head->next!=NULL){
head=head->next;
printf("%d ",head->data);
}
}
int main(){
node *head=creatnode(8);
print(head);
printf("\n");
head=reserve(head);
print(head);
return 0;
}