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?
Solution:
Python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
#运用迭代的方法
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
oldlist = head #oldlist定义的是原链表,也就是要反转的链表
newlist = None #newlist定义的是新链表,首先初始化为None
while oldlist != None: #然后开始遍历旧链表
temp = oldlist.next #定义一个暂时的链表存储oldlist.next开头的链表
oldlist.next = newlist #将oldlist的头结点作为newlist的头结点添加到newlist中
newlist = oldlist #更新新链表的头指针
oldlist = temp #将以oldlist.next开头的链表赋给oldlist,这个时候oldlist被更新,其头结点为原oldlist的第二个链表元素
return newlist #最终返回新链表
#运用递归的方法
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
newlist = self.reverseList(head.next) #遍历链表,找到链表的最后一个元素,赋给newlist
head.next.next = head #将本节点next指针指向本节点的前一个节点
head.next = None #将前一个节点指向本节点的next指针断开
return newlist #更新newlist
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) {
if (head == NULL || (head->next) == NULL){
return head;
}
ListNode *newlist = NULL;
while (head){
ListNode *temp = (head->next);
(head->next) = newlist;
newlist = head;
head = temp;
}
return newlist;
}
};
// 递归方法
class Solution{
public:
ListNode* reverseList(ListNode* head){
if (!head || !(head->next)){
return head;
}
ListNode* newlist = reverseList((head->next));
head->next->next = head;
head->next = NULL;
return newlist;
}
};
参考文献:https://blog.csdn.net/fx677588/article/details/72357389