#include <stdio.h>
#include <stdlib.h>
typedef struct Node{
struct Node * next;
int data;
}node;
node* reverse_list(node *head){
if(head==NULL || head->next == NULL)
return head;
node * cur = head;
node * next = head->next;
node * previous = NULL;
while(next!=NULL){
cur->next = previous;
previous = cur;
cur = next;
next = next->next;
}
cur->next = previous;
head = cur;
return cur;
}
void print_list(node *head){
while(head!=NULL){
printf("%d\t",head->data);
head = head->next;
}
printf("\n");
return;
}
int main(){
node *head,*tmp;
head = tmp = (node*) malloc(sizeof(node)) ;
head->data = 0;
int i;
for( i = 0;i<9;i++){
node *t = (node*) malloc(sizeof(node));
t->data = i+1;
tmp->next = t;
tmp = t;
}
tmp->next = NULL;
print_list(head);
head = reverse_list(head);
print_list(head);
return 0;
}
反转单向链表
最新推荐文章于 2025-04-25 17:53:22 发布