LeetCode刷题—翻转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
方法1;开辟新数组
对于一个长度为n的单链表head,用一个大小为n的数组arr储存从单链表从头
到尾遍历的所有元素,在从arr尾到头读取元素简历一个新的单链表
时间消耗O(n),空间消耗O(n)

def reverse_linkedlist1(head):
    if head == None or head.next == None: #边界条件
        return head
    arr = [] # 空间消耗为n,n为单链表的长度
    while head:
        arr.append(head.val)
        head = head.next
    newhead = ListNode(0)
    tmp = newhead
    for i in arr[::-1]:
        tmp.next = ListNode(i)
        tmp = tmp.next
    return newhead.next

2。新建表头翻转
开始以单链表的第一个元素为循环变量cur,并设置2个辅助变量tmp,保存数据;
newhead,新的翻转链表的表头。
时间消耗O(n),空间消耗O(1)

def reverse_linkedlist2(head):
    if head == None or head.next == None: #边界条件
        return head
    cur = head #循环变量
    tmp = None #保存数据的临时变量
    newhead = None #新的翻转单链表的表头
    while cur:
        tmp = cur.next 
        cur.next = newhead
        newhead = cur   # 更新 新链表的表头
        cur = tmp
    return newhead

3.就地反转
开始以单链表的第二个元素为循环变量,用2个变量循环向后操作,并设置1个辅助变量tmp,保存数据;时间消耗O(n),空间消耗O(1)

def reverse_linkedlist3(head):
    if head == None or head.next == None: #边界条件
        return head
    p1 = head #循环变量1
    p2 = head.next #循环变量2
    tmp = None #保存数据的临时变量
    while p2:
        tmp = p2.next
        p2.next = p1
        p1 = p2
        p2 = tmp
    head.next = None
    return p1

4.递归操作
递归操作,先将从第一个点开始翻转转换从下一个节点开始翻转
直至只剩一个节点时间消耗O(n),空间消耗O(1)


def reverse_linkedlist4(head):
    if head is None or head.next is None:
        return head
    else:
        newhead=reverse_linkedlist4(head.next)
        head.next.next=head
        head.next=None
    return newhead
 
        
def create_ll(arr):
    pre = ListNode(0)
    tmp = pre
    for i in arr:
        tmp.next = ListNode(i)
        tmp = tmp.next
    return pre.next
    
def print_ll(head):
    tmp = head
    while tmp:
        print tmp.val
        tmp=tmp.next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值