zoukankan      html  css  js  c++  java
  • 链表的部分翻转

    给定一个链表,翻转该链表从m到n的位置。要求直接翻转而非申请新空间。

    #include <iostream>
    #include <vector>
    #include <algorithm>
    #include <map>
    #include <cstdio>
    
    using namespace std;
    
    typedef struct tagSNode
    {
    	int  value;
    	tagSNode* pNext;
    
    	tagSNode(int v) :value(v), pNext(NULL){}
    }SNode;
    
    void Reverse(SNode* pHead, int from, int to)
    {
    	SNode* pCur = pHead->pNext;
    	int i;
    	for (i = 0; i<from - 1; i++)
    	{
    		pHead = pCur;
    		pCur = pCur->pNext;
    	}
    
    	SNode* pPre = pCur;
    	pCur = pCur->pNext;
    	to--;
    	SNode* pNext;
    	for (; i<to; i++)
    	{
    		//此处需要结合图示
    		pNext = pCur->pNext;
    		pCur->pNext = pHead->pNext;
    		pHead->pNext = pCur;
    		pPre->pNext = pNext;
    		pCur = pNext;
    	}
    }
    
    void Destroy(SNode* p)
    {
    	SNode* next;
    	while (p)
    	{
    		next = p->pNext;
    		delete p;
    		p = next;
    	}
    }
    
    int main()
    {
    	SNode* pHead = new SNode(0);
    	int i;
    	for (i = 0; i<10; i++)
    	{
    		SNode* p = new SNode(rand() % 100);
    		p->pNext = pHead->pNext;
    		pHead->pNext = p;
    	}
    	//Print(pHead);
    	Reverse(pHead, 4, 8);
    	//Print(pHead);
    	//Print(pHead);
    	Destroy(pHead);
    
    	return 0;
    }

    
                
    
  • 相关阅读:
    FL2440-学习记录(二)
    FL2440-学习记录(三)
    C专家编程 第一章
    C陷阱与缺陷
    ARM体系结构与编程-第二章
    二叉堆 及 大根堆的python实现
    八皇后问题
    非递归全排列 python实现
    Python 学习
    poj1064 Cable master(二分查找,精度)
  • 原文地址:https://www.cnblogs.com/muyangshaonian/p/9650552.html
Copyright © 2011-2022 走看看