反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解题思路:
Python:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: 'ListNode') -> 'ListNode':
if head == None:
return head
q = head
p = q.next
while (p):
temp = p.next
p.next = head
head = p
p = temp
q.next = None
return head
C++
方法一
想了一个笨办法,将每个节点的值保存在vector中,然后将vector反序,再将值写入对应的节点。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return NULL;
vector<int> listval;
ListNode* newhead = head;
while(newhead){
listval.push_back(newhead->val);
newhead = newhead->next;
}
reverse(listval.begin(), listval.end());
newhead = head;
for(auto val:listval){
newhead->val = val;
newhead = newhead->next;
}
return head;
}
};
方法二:
通过迭代求解。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode *newhead = head, *temp = NULL;
while(newhead){
newhead = head->next;
head->next = temp;
temp = head;
head = newhead;
}
return temp;
}
};
方法三
递归解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode *node = reverseList(head->next);
head->next->next = head;
head -> next = NULL;
return node;
}
};