13.反转链表
来源:互联网 发布:广州java开发外包人力 编辑:程序博客网 时间:2024/06/10 00:46
反转链表
- 参与人数:5997时间限制:1秒空间限制:32768K
- 算法知识视频讲解
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
这道题我做了近40分钟,对链表的插入操作不熟悉!
// 12.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stack>using namespace::std;struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};class Solution {public:ListNode* ReverseList(ListNode* pHead) {if (!pHead) return NULL;stack<ListNode*> stack;ListNode* pNode = pHead;while (pNode) {stack.push(pNode);pNode = pNode->next;}ListNode* pNew = stack.top();stack.pop();ListNode* tmp = pNew;while (!stack.empty()) {ListNode* node = stack.top();node->next = pNew->next;pNew->next = node;pNew = pNew->next;stack.pop();}//pNew = tmp;return tmp;}};int _tmain(int argc, _TCHAR* argv[]){ListNode n1(1);ListNode n2(2);ListNode n3(3);ListNode n4(4);ListNode n5(5);n1.next = &n2;n2.next = &n3;n3.next = &n4;n4.next = &n5;Solution s;s.ReverseList(&n1);return 0;}
while (!stack.empty()) {ListNode* node = stack.top();node->next = pNew->next;pNew->next = node;pNew = pNew->next;stack.pop();}
第二次做:
/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution {public: ListNode* ReverseList(ListNode* pHead) {if ( pHead == NULL ) return NULL ; vector<int> vec ; ListNode* pNode = pHead ; while ( pNode != NULL ) { vec.push_back( pNode -> val ) ; pNode = pNode -> next ; } ListNode* pNew = new ListNode( vec[ vec.size() - 1 ] ) ; ListNode* pCur = pNew ; for ( int i = vec.size() - 2; i >= 0; -- i ) { ListNode* tmp = new ListNode( vec[i] ) ; pCur -> next = tmp ; pCur = pCur -> next ; } return pNew ; }};while循环中我忘了
pNode = pNode -> next ;
。。。下次注意!
第三次做:
/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution {public: ListNode* ReverseList(ListNode* pHead) {if ( pHead == NULL ) return NULL ; vector<int> vec ; ListNode* pNode = pHead ; while ( pNode != NULL ) { vec.push_back( pNode->val ) ; pNode = pNode->next ; } std::reverse( vec.begin(), vec.end() ) ; ListNode* pNew = new ListNode( vec[0] ) ; ListNode* pCur = pNew ; for ( int i = 1; i < vec.size(); ++ i ) { ListNode* tmp = new ListNode( vec[i] ) ; pCur->next = tmp ; pCur = pCur->next ; } return pNew ; }};
0 0
- 13.反转链表
- 链表反转
- 反转链表
- 单向链表反转
- 链表反转:
- 链表的反转
- 链表反转
- 反转单向链表
- 链表反转
- 单向链表反转
- 单向链表反转
- 链表的反转
- 链表反转
- 反转链表
- 链表反转
- 链表反转
- 链表反转
- 链表反转
- 80. Remove Duplicates from Sorted Array II
- RGB vs YCbCr(YUV)
- php和Apache搭建笔记
- Android广播机制总结
- 【HUSTOJ】1026: 判断素数
- 13.反转链表
- 时代浪潮
- HDU 1233 还是畅通工程(最小生成树)
- Xcode Build Search Paths设置
- Centos安装配置Mysql,以及防火墙的设置
- HTML5----响应式(自适应)网页设计
- Nodejs学习item 2 -- events事件处理EventEmitter
- android:exported 属性详解
- linux下c++编程环境搭建,运行过程以及调试