当前位置:编程学习 > C/C++ >>

带头的单链表的逆转

自己写了单链表的逆转程序,记录如下,欢迎指正
 
#include   <iostream> 
using   namespace   std; 
struct Node 

    int data; 
    Node *next; 
}; 
 
Node * reverse(Node *head) 

    if(head->next==NULL) 
        return head; 
    Node *t1=head->next; 
    if(t1==NULL) 
        return head; 
    Node *t2=t1->next; 
    t1->next=NULL; 
    while(t2->next!=NULL) 
    { 
        Node *t3=t2->next; 
        t2->next=t1; 
        t1=t2; 
        t2=t3; 
    } 
    t2->next=t1; 
    head->next=t2; 
    return head; 
 

 
 
void main() 

    Node *list=new Node[5]; 
    Node *head=new Node; 
    head->next=&list[0]; 
    list[0].data=1; 
    list[0].next=&list[1]; 
    list[1].data=2; 
    list[1].next=&list[2]; 
    list[2].data=3; 
    list[2].next=&list[3]; 
    list[3].data=4; 
    list[3].next=&list[4]; 
    list[4].data=5; 
    list[4].next=NULL; 
    Node *p; 
    p=head; 
    while(p->next!=NULL) 
    { 
        printf("%d\n",p->next->data); 
        p=p->next; 
    } 
 
    reverse(head); 
    printf("逆转后\n"); 
    p=head; 
    while(p->next!=NULL) 
    { 
        printf("%d\n",p->next->data); 
        p=p->next; 
    } 
    delete head; 
    delete []list; 

运行结果:

作者“菜鸟变身记”

补充:软件开发 , C语言 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,