俊介三

一天更新一点,一天积累一点

导航

颠倒一个链接表的顺序

Posted on 2013-03-28 12:03  俊介三在前进  阅读(278)  评论(0)    收藏  举报

用一种算法来颠倒一个链接表的顺序。递归和不递归的方法:

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

struct List{
    int data;
    List* next;
    List(){}
    List(int d){
        data = d;
        next = NULL;
    }
    List(int d, List* list){
        data =d;
        next = list;
    }
};

//append an element to tail
List* appendToTail(int data, List* head){
    List* tail = new List(data,NULL);
    List* p = head;
    while(p->next!=NULL){
        p = p->next;
    }
    p->next = tail;
    return head;
}

void print(List* head){
    while(head!=NULL){
        printf("%d ",head->data);
        head = head->next;
        if(head==NULL) puts("");
    }
}

List* reverse(List* head){
    if(head==NULL || head->next==NULL) return head;
    List* newhead = reverse(head->next);
    head->next->next = head;
    head->next = NULL;
    return newhead;
}

List* reverse_recursive(List* head){
    List* h = head;
    List* previous = NULL;
    List*  temp;
    while(h->next!=NULL){
        temp = h->next;
        h->next = previous;
        previous = h;
        h = temp;
    }
    h->next = previous;
    return h;
}

int main(){
    List* node = new List(12);
    List* head = appendToTail(23,node);
    head = appendToTail(14,head);
    head = appendToTail(50,head);
    
    print(node);
    node = reverse(node);
    print(node);
    node  =reverse_recursive(node);
    print(node);

    return 0;
}