单链表逆序

来源:互联网 发布:python灰帽子 源码 编辑:程序博客网 时间:2024/04/29 19:33

//已知链表的头结点head,写一个函数把这个链表逆序 ( Intel)  
#include <iostream>  
 
using namespace std;  
 
struct Node  
{  
    int data ;  
    Node *next ;  
};  
typedef struct Node Node ;  
 
Node* ReverseList(Node* head)  
{  
    if (!head || !head->next)  
    {  
        return head;  
    }  
    Node* p1 = head;  
    Node* p2 = p1->next;  
    head->next = NULL;  
    while (p2)  
    {  
          
        p1 = p2;  
        p2 = p2->next;  
        p1->next = head;  
        head = p1;  
    }  
    return head;  
}  
 
Node* RecReverseList(Node* head) //递归方法1  
{     
    if (!head || !head->next)  
    {  
        return head;  
    }  
    Node *newhead = RecReverseList(head->next);  
    head->next->next = head;  
    head->next = NULL;  
    return newhead;  
}   

node* reverse(node * head)     //递归方法2
{
  if(head==NULL || head->next==NULL)
     return head;
  node* tail= head->next;
  node* newHead= reverse(head->next);
  tail->next=head;
  head->next=NULL;
  return newHead;
}
                        
void main()  
{  
    Node a, b, c;  
    a.data = 1, a.next = &b;  
    b.data = 2, b.next = &c;  
    c.data = 3, c.next = NULL;  
    Node* tmp = &a;  
    while(tmp)  
    {  
        cout<<tmp->data<<" ";  
        tmp = tmp->next;  
    }  
    cout<<endl;  
    tmp = RecReverseList(&a);  
    while(tmp)  
    {  
        cout<<tmp->data<<" ";  
        tmp = tmp->next;  
    }  
    cout<<endl;  


本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/raul23551984/archive/2009/07/08/4330181.aspx

原创粉丝点击