-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathoffer3.cpp
56 lines (47 loc) · 1.21 KB
/
offer3.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*******************************************************************
* 题目:输入一个链表的头结点,从尾到头反过来打印每个节点的值
********************************************************************/
/**
* struct ListNode{
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
**/
//方法一:使用stack
vector<int> printListFromTailToHead(ListNode *head){
if(head==NULL)
return vector<int>();
stack<int> nodes;
ListNode* pNode=head;
while(pNode!=NULL){
nodes.push(pNode->val);
pNode=pNode->next;
}
vector<int> ret;
while(!nodes.empty()){
ret.push_back(nodes.top());
nodes.pop()
}
return ret;
}
//方法二:逆置链表,然后输出
vector<int> printListFromTailToHead(ListNode* head){
if(head==NULL)
return vector<int>();
ListNode* pNode=head;
ListNode* pre=pNode;
while(pre->next){
pNode=pre->next;
pre->next=pNode->next;
pNode->next=head;
head=pNode;
}
vector<int> ret;
pNode=head;
while(pNode){
ret.push_back(pNode->val);
pNode=pNode->next;
}
return ret;
}