链表的部分翻转
链表相加:
给定一个链表,翻转该链表从m到n的位置。要求直接翻转而非申请新空间。
如:给定:1->2->3->4->5,m=2,n = 4.
返回:1->4->3->2->5.
程序实现:
1 /************************************ 2 File Name:ListPartReverse.cpp 3 Author: godfrey 4 Created Time: 2016/04/28 5 *************************************/ 6 #include <iostream> 7 #include <cstdio> 8 #include <cstdlib> 9 using namespace std; 10 11 typedef struct tagSNode{ 12 int value; 13 tagSNode* pNext; 14 15 tagSNode(int v):value(v),pNext(NULL) {} 16 }SNode; 17 //打印链表 18 void Print(SNode* pHead){ 19 SNode* p = pHead->pNext; 20 while(p){ 21 cout<<p->value<<" "; 22 p = p->pNext; 23 } 24 cout<<endl; 25 } 26 //删除分配结点空间 27 void Destroy(SNode* pHead){ 28 SNode* p; 29 while(pHead){ 30 p = pHead->pNext; 31 delete pHead; 32 pHead = p; 33 } 34 } 35 //链表部分翻转 36 void ListPartReverse(SNode* pHead,int from,int to){ 37 SNode* pCur = pHead->pNext; 38 int i; 39 for(i=0;i<from-1;i++){ 40 pHead = pCur; 41 pCur = pCur->pNext; 42 } 43 44 SNode* pPre = pCur; 45 pCur = pCur->pNext; 46 SNode* t = NULL; 47 for(;i<to-1;i++){ 48 t = pCur->pNext; 49 pCur->pNext = pHead->pNext; 50 pHead->pNext = pCur; 51 pPre->pNext = t; 52 pCur = t; 53 } 54 } 55 56 57 int main() 58 { 59 SNode* pHead = new SNode(0); 60 for(int i=0;i<10;i++){ 61 SNode* p = new SNode(rand()%100); 62 p->pNext = pHead->pNext; 63 pHead->pNext = p; 64 } 65 66 Print(pHead); 67 ListPartReverse(pHead,4,8); 68 Print(pHead); 69 Destroy(pHead); 70 return 0; 71 }
运行结果:
转载请注明出处:
C++博客园:godfrey_88
http://www.cnblogs.com/gaobaoru-articles/
posted on 2016-04-28 22:17 Brainer-Gao 阅读(393) 评论(0) 编辑 收藏 举报