面试题16:反转链表
来源:互联网 发布:网络it需要什么学历 编辑:程序博客网 时间:2024/04/19 22:25
#include<iostream>using namespace std;struct Node{ int nValue; Node *pNext;};void CreateList(Node **pHead,Node **pEnd,int n){ int nValue; for(int i=0;i<n;i++) { cin>>nValue; Node *temp = new Node; temp->nValue = nValue; temp->pNext = NULL; if((*pHead) == NULL) { (*pHead) = temp; } else { (*pEnd)->pNext = temp; } (*pEnd) = temp; }}Node* ReverseList(Node *pHead,Node *pEnd){ Node *pPrev = NULL;//记录前一个节点 Node *temp = pHead;//记录当前结点 Node *pNext = NULL;//记录下一个节点 Node *pReverseHead = NULL;//记录反转链表的头结点地址 while(temp) { pNext = temp->pNext; if(pNext == NULL) { pReverseHead = temp; } temp->pNext = pPrev;//更改指针 pPrev = temp;//交替更换 pPrev 和 temp指针 temp = pNext; } return pReverseHead;}int main(){ int n; while(cin>>n) { Node *pHead = NULL; Node *pEnd = NULL; CreateList(&pHead,&pEnd,n); Node *temp = pHead; while(temp) { cout<<temp->nValue<<" "; temp = temp->pNext; } Node *ReverseHead = ReverseList(pHead,pEnd); cout<<endl<<"--------------------------"<<endl; while(ReverseHead) { cout<<ReverseHead->nValue<<" "; ReverseHead = ReverseHead->pNext; } } return 0;}
//递归版本
Node *Reverse_List(Node *pHead)
{
<span style="white-space:pre"></span>if(pHead == NULL || pHead->pNext == NULL)
<span style="white-space:pre"></span>{
<span style="white-space:pre"></span>return pHead;
<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>Node *NewHead = Reverse_list(pHead->pNext);
pHead->next->next = pHead;
<span style="white-space:pre"></span>pHead = pHead->pNext;
<span style="white-space:pre"></span>return NewHead;
}
1 0
- 面试题16:反转链表
- 面试题16 反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16:反转链表(java)
- 面试题16:反转链表
- 面试题16:反转链表
- 面试题16反转链表
- 面试题16:反转链表
- 【面试题16】反转链表
- Android Service之串行化Service:IntentService(系列3)
- C++ 中的 Lambda 表达式
- regular polygon can be drawn only by straightedge and compass
- Xcode或模拟器运行时错误总结
- MapReduce架构
- 面试题16:反转链表
- 大扫除与代码重构
- PHP 函数ignore_user_abort ()
- ios学习之uisplitview的自定义代理的学习
- Struts2上传文件
- android WebView总结
- 编译原理中的正规表达式转NFA
- Duplicate application configs: <dubbo:application错误
- iOS——LLVM、Clang浅析