LeetCode——反转链表
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
解法一:迭代法
我们遍历整个链表,将链表中的值全部按顺序存储在一个列表num中,然后我们将这个列表num逆序,再次遍历链表,再将所有值依次改写成列表num中的值,以此实现链表逆序的操作。
解法二:递归法
1->2->3->4->5->NULL
我们以这个链表进行举例:我们要做的就是改写这些箭头的顺序,假设我们head到了3这个节点,后面的两个节点已经逆序成5, 4(newhead = self.reverseList(head.next))。那么我们要做的就是改写3前面那个箭头的顺序,也就是head.next.next = head,注意,在这之后我们需要断开2到3这个箭头,也就是head.next = None,否则就会形成回路。我们要返回操作后链表的头结点,即newhead。最后我们确定递归结束的条件,即(head is None or head.next is None),我们直接返回head。
迭代法python代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
i = head
num = []
while i:
num.append(i.val)
i = i.next
num.reverse()
i = head
j = 0
while i:
i.val = num[j]
i = i.next
j += 1
return head
递归法python代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None or head.next is None:
return head
newhead = self.reverseList(head.next)
head.next.next = head
head.next = None
return newhead