Problem Solving using C++

Algorithm Study using C++

单链表的翻转

非常简单的实现,设置3个指针,分别指向当前节点、前一个节点、后一个节点,然后依次处理所有的节点就OK了。
具体代码为:
#include <iostream>

using namespace std;

#ifndef 
null
#define 
null (void*)0
#endif

typedef struct node
{
    struct node
* next;
    
int data;
}node;

node
* head=(node*)null;

void reverse(node* root)
{
    node 
*cur,*pre,*next;
    
    pre
=(node*)null;
    cur
=root;
    next
=cur->next;
    
    
while(next)
    {
        cur
->next=pre;
        pre
=cur;
        cur
=next;
        next
=cur->next;
    }
    
    head
=cur;
    cur
->next=pre;
}

void insert(node* p)
{
    p
->next=head;
    head
=p;
}

void del(node* p)
{
    node 
*cur,*next;
    cur
=p;
    next
=p->next;
    
    
while(next)
    {
        delete cur;
        cur
=next;
        next
=cur->next;
    }
    
    delete cur;
}

void print(node* p)
{
    
while(p)
    {
        cout
<<p->data<<" ";
        p
=p->next;
    }
    
    cout
<<endl;
}

int main(int argc,char** argv)
{
    
for(int i=0;i<10;i++)
    {
        node
* p=new node;
        p
->next=(node*)null;
        p
->data=i;
        
        insert(p);
    }
    print(head);
    cout
<<"reverse order:"<<endl;
    
    reverse(head);
    print(head);
    
    del(head);
    
    
    system(
"pause");
    
return 0;
}


posted on 2007-09-05 14:41 Kingoal Lee's Alogrithm Study using cplusplus 阅读(2005) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


My Links

Blog Stats

常用链接

留言簿(1)

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜