码迷,mamicode.com
首页 > 其他好文 > 详细

链表的部分翻转

时间:2016-04-28 22:35:20      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

链表相加:

给定一个链表,翻转该链表从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 }

运行结果:

技术分享

转载请注明出处:http://www.cnblogs.com/gaobaoru-articles/

链表的部分翻转

标签:

原文地址:http://www.cnblogs.com/gaobaoru-articles/p/5444519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!