Please enable Javascript to view the contents

剑指office(十五)反转链表

 ·  ☕ 1 分钟  ·  🎅 YSL

题目描述

输入一个链表,反转链表后,输出新链表的表头。

示例1

输入

{1,2,3}

返回值

{3,2,1}
 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
/*
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*> stackNode;
        while(pHead)
        {
            stackNode.push(pHead);
            pHead = pHead->next;
        }
        ListNode* result = stackNode.top();
        stackNode.pop();
         ListNode* cur = result;
        int S = stackNode.size();
        for(int i = 0;i<S;i++)
        {
           cur->next = stackNode.top();
            stackNode.pop();
            cur = cur->next;
        }
        cur->next = NULL;
        return result;
    }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* nextNode = NULL;
        ListNode* currentNode = pHead;
        ListNode* reverseNode = NULL;
        while(currentNode)
        {
            nextNode = currentNode->next;
            currentNode->next = reverseNode;
            reverseNode = currentNode;
            currentNode = nextNode;
        }
        return reverseNode;
    }
};