反转链表
- 参与人数: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 ;
}
};