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

写一个递归版本的链表转置程序

链表的转置是一个很常见、很基础的数据结构题了,非递归的算法很简单,用三个临时指针在链表上循环一遍即可,不再赘述。递归算法也是比较简单的,但是如果思路不清晰估计也难一时半会儿写出来把。下面是递归版本的链表转置程序:


[cpp] 
#include <iostream>  
using namespace std; 
 
typedef struct Node 

    Node(int v, Node *ptr=NULL) : data(v), next(ptr) {} 
    int data; 
    Node *next; 
}sNode; 
 
//LB_c: 输出链表,head为链表头指针  
void outputList(sNode *head) 

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

 
//LB_c: 转置链表的递归方法实现  
sNode* reverseList(sNode *head) 

    //LB_c: 异常判断(NULL==head)结束条件(NULL==head->nex),  
    // 即head为最后一个节点时,将该节点返回,即为转置链表的头节点。  
    if ( (NULL == head) || (NULL == head->next) ) 
    return head; 
    //LB_c: 递归后续链表(即以head->next为首节点的链表)  
    sNode *pNewHead = reverseList(head->next); 
    //LB_c: 上一步执行完后,head->next为后续链表的末尾节点,  
    //所以让head->next的next指向当前节点head  
    head->next->next = head; 
    //LB_c: 当前节点的next指向NULL  
    head->next = NULL; 
    //LB_c: 返回后续链表的头指针  
    return pNewHead; 

 
int main() 

    //LB_c: 创建链表  
    sNode n5(5); 
    sNode n4(4, &n5); 
    sNode n3(3, &n4); 
    sNode n2(2, &n3); 
    sNode n1(1, &n2); 
 
    //LB_c: 输出原始链表  
    outputList(&n1); 
 
    //LB_c: 调用转置函数  
    sNode *pNew = reverseList(&n1); 
 
    //LB_c: 输出转置后的链表  
    outputList(pNew); 
 
    return 0; 

#include <iostream>
using namespace std;

typedef struct Node
{
    Node(int v, Node *ptr=NULL) : data(v), next(ptr) {}
    int data;
    Node *next;
}sNode;

//LB_c: 输出链表,head为链表头指针
void outputList(sNode *head)
{
    sNode *p = head;
    while (p != NULL)
    {
 cout << p->data << " -> ";
 p = p->next;
    }
    cout << "NULL" << endl;
}

//LB_c: 转置链表的递归方法实现
sNode* reverseList(sNode *head)
{
    //LB_c: 异常判断(NULL==head)结束条件(NULL==head->nex),
    // 即head为最后一个节点时,将该节点返回,即为转置链表的头节点。
    if ( (NULL == head) || (NULL == head->next) )
 return head;
    //LB_c: 递归后续链表(即以head->next为首节点的链表)
    sNode *pNewHead = reverseList(head->next);
    //LB_c: 上一步执行完后,head->next为后续链表的末尾节点,
    //所以让head->next的next指向当前节点head
    head->next->next = head;
    //LB_c: 当前节点的next指向NULL
    head->next = NULL;
    //LB_c: 返回后续链表的头指针
    return pNewHead;
}

int main()
{
    //LB_c: 创建链表
    sNode n5(5);
    sNode n4(4, &n5);
    sNode n3(3, &n4);
    sNode n2(2, &n3);
    sNode n1(1, &n2);

    //LB_c: 输出原始链表
    outputList(&n1);

    //LB_c: 调用转置函数
    sNode *pNew = reverseList(&n1);

    //LB_c: 输出转置后的链表
    outputList(pNew);

    return 0;
}


 

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