有题目的需求是求将链表反转,例如1->2->3->4->5转变成5->4->3->2->1,经典的是可以有两种解决方法,递归方式和非递归方式,下面给出C++的这两周实现过程。
#include<iostream> using namespace std; const int N = 6; typedef int DataType;//定义数据类型 typedef struct node{//创建链表node DataType data; struct node* next; }LinkedNode,*LinkList; LinkList CreateList(DataType a[N])//建表函数 { LinkedNode* ListHead = new LinkedNode(); ListHead->data= a[0]; ListHead->next= NULL; for(int i = N - 1;i >= 1;i --) { LinkedNode* p = new LinkedNode(); p->data = a[i]; p->next = ListHead->next; ListHead->next = p; } return ListHead; } void PrintList(LinkList ListHead)//实现的一个输出表的函数 { if(ListHead == NULL) cout<<"This is empty list"<<endl; else { LinkedNode* p = ListHead; while(p != NULL) { cout<<p->data<<" "; p = p->next; } cout<<endl; } } void RecReverseList(LinkedNode* pCur,LinkList& ListHead)//递归实现表的反转 { if( (NULL == pCur) || (NULL == pCur->next) ) { ListHead = pCur; } else { LinkedNode* pNext = pCur->next; RecReverseList(pNext,ListHead); pNext->next = pCur; pCur->next= NULL; } } void UnRecReverseList(LinkList& ListHead)//非递归实现表的反转 { if(NULL == ListHead) return ; LinkedNode *pre,*cur,*nex; pre = ListHead; cur = pre->next; while(cur) { nex = cur->next; cur->next = pre; pre = cur; cur = nex; } ListHead->next= NULL; ListHead = pre; } int main() { int a[N] = {1,2,3,4,5,6}; LinkedNode* list = CreateList(a); PrintList(list); LinkedNode* pTemp = list; RecReverseList(pTemp,list); PrintList(list); UnRecReverseList(list); PrintList(list); return 0; }
运行结果: