反转单向链表

#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;
}

猜你喜欢

转载自blog.csdn.net/juiceda/article/details/7607886