您的位置:首页 > 其它

逆序链表--递归思路

2013-03-27 00:00 239 查看
今天同学问的问题,猛然一想,还不太容易想到,记录下吧。。。

#include <iostream>

using namespace std;

struct ListNode{
int m_nKey;
ListNode* m_pNext;
};

bool creatList(ListNode *&head,int *index,int length){
if(length<0){
return false;
}
ListNode *pPre = head;
for(int i = 0 ; i < length ; ++i){
ListNode *pNewListNode = new ListNode;
pNewListNode->m_nKey = index[i];
pNewListNode->m_pNext = NULL;
pPre->m_pNext = pNewListNode;
pPre = pNewListNode;
}
return true;
}

ListNode * re(ListNode *pCurrent,ListNode *&head){//递归逆序链表
if(pCurrent->m_pNext == NULL){
head = pCurrent;
return pCurrent;
}
ListNode * pTemp = re(pCurrent->m_pNext,head);
pTemp->m_pNext = pCurrent;
return pCurrent;
}

void disPlay(ListNode *head){
while(head != NULL){
cout << head->m_nKey << " ";
head = head->m_pNext;
}
cout << endl;
}

int main(){
int index[5] = {1,2,3,4,5};
ListNode* pHead = new ListNode;
ListNode* pLast;
creatList(pHead,index,5);
re(pHead->m_pNext,pHead->m_pNext)->m_pNext = NULL;
disPlay(pHead->m_pNext);
system("pause");
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: