此题链接:Reverse Linked List - LeetCode
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
这是一道经典的反转链表的题,有递归和迭代2种做法,其中使用递归可以只使用一个中间临时变量。
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:
prev = None
curr = head
while curr != None:
nextNode = curr.next
curr.next = prev
prev = curr
curr = nextNode
return prev
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 or head.next == None):
return head
node = self.reverseList(head.next)
head.next.next = head
head.next = None
return node
C++迭代做法:
/**
* 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)
{
ListNode *prev = NULL;
ListNode *curr = head;
while (curr != NULL)
{
ListNode *nextnode = curr->next;
curr->next = prev;
prev = curr;
curr = nextnode;
}
return prev;
}
};