链表的翻转与排序

面试中常常会考到链表的翻转和排序,在此手动实现了一发,希望能对大家产生帮助

 

#include <iostream>
using namespace std;

template<class T>
struct Node
{
    Node<T>* pNext;
    T val;
};

template<typename T>
void append(Node<T>* head,T val)//添加节点
{
    while(head->pNext!=NULL)
    {
        head=head->pNext;
    }
    Node<T> *pNode = (struct Node<T>*)malloc(sizeof(struct Node<T>*));
    pNode->val=val;
    pNode->pNext=NULL;
    head->pNext=pNode;
}

template<typename T>
void show(Node<T>* head)//显示链表
{
    while(head->pNext!=NULL)
    {
        head=head->pNext;
        cout<<head->val<<" ";
    }
}

template<typename T>
Node<T>* reverseRec(Node<T>* Head,Node<T>* CNode,Node<T>* Prev)//链表翻转递归法
{
    if(CNode->pNext!=NULL)
    {
        Node<T>* pNode=reverseRec(Head,CNode->pNext,CNode);
        if(Prev==Head)
            CNode->pNext=NULL;
        else
            CNode->pNext=Prev;
        return pNode;
    }
    else
    {
        CNode->pNext=Prev;
        return CNode;
    }
}

template<typename T>
void reverseOde(Node<T>* pHead)//链表翻转非递归法
{
    if(pHead==NULL||pHead->pNext==NULL)
        return;
    Node<T>* pTem=pHead->pNext;
    Node<T>* pTemPre =pHead;
    Node<T>* pTemNe;
    while(pTem->pNext!=NULL)
    {
        pTemNe=pTem->pNext;
        if(pTemPre==pHead)
            pTem->pNext=NULL;
        else
            pTem->pNext=pTemPre;
        if(pTemNe->pNext==NULL)
            break;
        pTemPre=pTem;
        pTem=pTemNe;
    }
    pTemNe->pNext=pTem;
    pHead->pNext=pTemNe;
}

template<typename T>
inline void exchange(Node<T>* pNode1Pre,Node<T>* pNode1,Node<T>* pNode2)//节点交换
{
    pNode1Pre->pNext=pNode2;
    pNode1->pNext=pNode2->pNext;
    pNode2->pNext=pNode1;
}

template<typename T>
void ListBoubleSort(Node<T>* pHead)//冒泡排序
{
    Node<T>* pNode1;
    Node<T>* pNode2;
    Node<T>* pNode2Pre;
    pNode1=pHead->pNext;
    while(pNode1->pNext!=NULL)
    {
        pNode1=pNode1->pNext;
        pNode2=pHead->pNext;
        pNode2Pre=pHead;
        while(pNode2->pNext!=NULL)
        {
            if(pNode2->val>pNode2->pNext->val)
            {
                exchange(pNode2Pre,pNode2,pNode2->pNext);
                pNode2=pNode2Pre->pNext;  //指针要指回之前的位置
            }
            pNode2Pre=pNode2Pre->pNext;
            pNode2=pNode2->pNext;
        }
    }
}

int main()
{
    Node<int> *pHead = (struct Node<int>*)malloc(sizeof(struct Node<int>*));
    pHead->pNext=NULL;
    for(int i=15;i>0;i--)
        append(pHead,i);

    show(pHead);
    cout<<endl;

    pHead->pNext=reverseRec(pHead,pHead->pNext,pHead);//递归翻转,返回尾节点
    show(pHead);
    cout<<endl;

    reverseOde(pHead);//非递归翻转
    show(pHead);
    cout<<endl;

    ListBoubleSort(pHead);//冒泡排序
    show(pHead);
    cout<<endl;

    return 0;
}

 

posted @ 2015-07-24 19:50  伟gg  阅读(306)  评论(0编辑  收藏  举报