zoukankan      html  css  js  c++  java
  • 面试经典题单链表反转

    struct node{
    	node* next;
    	T value;
    };

    方法一:常规方法

    node* reverse(node*& head)
    {
            if ( (head == Null) || (head->next == Null) ) return head;// 边界检测
            node* pNext = Null;
            node* pPrev = head;// 保存链表头节点
            node* pCur = head->next;// 获取当前节点
            while (pCur != Null)
            {
                pNext = pCur->next;// 将下一个节点保存下来
                pCur->next = pPrev;// 将当前节点的下一节点置为前节点
                pPrev = pCur;// 将当前节点保存为前一节点
                pCur = pNext;// 将当前节点置为下一节点
            }
    	head->next = NULL;
    	head = pPrev; 
    
    	return head;
    }

    方法二:递归

      node* reverse( node* pNode, node*& head)
     {
            if ( (pNode == Null) || (pNode->next == Null) ) // 递归跳出条件
            {
                head = pNode; // 将链表切断,否则会形成回环
                return pNode;
            }
    
            node* temp = reserve(pNode->next, head);// 递归
            temp->next = pNode;// 将下一节点置为当前节点,既前置节点
            return pNode;// 返回当前节点
     }
  • 相关阅读:
    做人做事
    不骄不躁
    争取
    收入
    Windows 7下的Comodo Firewall免费防火墙
    成功水平
    成家立业
    Windows无法安装到GPT格式磁盘的根本解决办法
    安装Windows10操作系统
    安装操作系统的几种方式
  • 原文地址:https://www.cnblogs.com/caleb/p/2036939.html
Copyright © 2011-2022 走看看