24.单链表就地逆制

/*
    单链表的就地逆制
 */

#include<iostream>
using namespace std;

typedef struct node
{
    int value;
    struct node* next;
}Node;

//头指针
Node* head=NULL;

void reverse()
{
    Node *p,*q;

    p=head;
    head=NULL;
    while(p!=NULL)
    {
        q=p;
        p=p->next;

        //把q插自head之前
        q->next=head;
        head=q;
    }

    //print
    p=head;
    while(p!=NULL)
    {
        cout<<p->value<<" ";
        p=p->next;
    }
    cout<<endl;
}

void init_list(int n)
{
    int i;
    head=new Node;
    head->value=0;
    head->next=NULL;

    Node* tail=head;
    for(i=1;i<n;i++)
    {
        Node* temp=new Node;
        temp->value=i;
        temp->next=NULL;
        
        tail->next=temp;
        tail=temp;
    }

    Node* p=head;
    while(p!=NULL)
    {
        cout<<p->value<<" ";
        p=p->next;
    }
    cout<<endl;
}

void free_list()
{
    Node *p,*q;

    p=head;
    while(p!=NULL)
    {
        q=p;
        p=p->next;
        delete q;
        q=NULL;
    }
}

int main(void)
{
    int n;
    cin>>n;

    init_list(n);
    reverse();
    free_list();
    return 0;
}

 

posted on 2013-08-16 15:52  紫金树下  阅读(299)  评论(0编辑  收藏  举报