1.7python如何把链表相邻元素翻转

题目描述:

把链表相邻元素翻转,例如给定链表为1->2->3->4->5->6->7,则翻转后的链表为2->1->4->3->6->5->7

方法:

1. 交换值法

最容易想到的方法就是交换相邻两个结点的数据域。这种方法由于不需要重新调整链表的结构,所以比较容易实现。

2. 就地逆序

通过调整结点指针域的指向来直接调换相邻的两个结点。如果单链表恰好有偶数个结点,那么只需要将奇偶结点对调即可;如果链表有奇数个结点,那么只需要将除最后一个结点外的其它结点进行奇偶对调即可。见下图:
在这里插入图片描述
在上图中,当前遍历到结点cur,通过(1)–(6)用虚线的指针来代替实线的指针实现相邻结点的逆序。其中,(1)–(4)实现了前两个结点的逆序操作,(5)和(6)两个步骤向后移动指针,接着可以采用同样的方式实现后面两个相邻结点的逆序操作。

算法性能分析:

这种方法只需要对链表进行一次遍历,所以时间复杂度为O(n);
另外由于只需要几个指针变量来保存结点的地址结点,所以空间复杂度为O(1)

代码实现:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2020/1/17 11:00
# @Author  : buu
# @Software: PyCharm
# @Blog    :https://blog.csdn.net/weixin_44321080
class LNode:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def reverse(head):
    """
    把链表相邻元素翻转
    :param head: 头结点
    :return:
    """
    if head is None or head.next is None:
        return
    cur = head.next  # 当前遍历结点
    pre = head  # 当前结点的前驱结点
    next = None  # 当前结点后继结点的后继结点
    while cur != None and cur.next != None:
        next = cur.next.next  # (1)
        pre.next = cur.next  # (2)
        cur.next.next = cur  # (3)
        cur.next = next  # (4)
        pre = cur  # (5)
        cur = next  # (6)


if __name__ == '__main__':
    i = 1
    head = LNode()
    tmp = None
    cur = head
    while i < 8:
        tmp = LNode(i)
        cur.next = tmp
        cur = tmp
        i += 1
    print('print in order:', end=' ')
    cur = head.next
    while cur is not None:
        print(cur.data, end=' ')
        cur = cur.next
    reverse(head)
    print('\nprint in reverse:', end=' ')
    cur = head.next
    while cur is not None:
        print(cur.data, end=' ')
        cur = cur.next

结果:
在这里插入图片描述
end

发布了76 篇原创文章 · 获赞 2 · 访问量 2576

猜你喜欢

转载自blog.csdn.net/weixin_44321080/article/details/104015504