zoukankan      html  css  js  c++  java
  • 1.7交换链表中的相邻节点

    交换链表中的相邻节点

    题目描述:

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

    解题思路:

    就地逆序法:

    通过调整结点指针域的指向来直接调换相邻的两个结点。如果单链表恰好有偶数个结点,那么只需要将奇偶结点对调即可,如果链表有奇数个结点,那么只需要将除最后一个结点外的其它结点进行奇偶对调即可。

    代码实现:

    # -*-coding:utf-8-*- 
    """
    @Author  : 图南
    @Software: PyCharm
    @Time    : 2019/9/6 18:34
    """
    class Node:
        def __init__(self, data=None, next=None):
            self.data = data
            self.next = next
    
    
    def print_link(head):
        if head is None or head.next is None:
            return None
        cur = head.next
        while cur.next != None:
            print(cur.data, end=' ')
            cur = cur.next
        print(cur.data)
    
    
    def con_link(n):
        head = Node()
        cur = head
        for i in range(1, n+1):
            node = Node(i)
            cur.next = node
            cur = node
        return head
    
    
    def reverseNode(head):
        pre = head
        cur = pre.next
        while cur is not None and cur.next is not None:
            next = cur.next
            pre.next = next
            cur.next = next.next
            next.next = cur
            pre = cur
            cur = pre.next
        return head
    
    
    if __name__ == '__main__':
        head = con_link(6)
        print_link(head)
        head = reverseNode(head)
        print_link(head)
    

    运行结果:


  • 相关阅读:
    Java设置环境变量
    php 生成二维码
    php 生成读取csv文件并解决中文乱码
    php 过滤重复的数组
    php 读取,生成excel文件
    php 逐行读取文本文件
    php 多维数组按键值分类
    python学习,day2:利用列表做购物车实例
    python学习,day1作业:设计一个三级菜单
    python学习,day2:字典
  • 原文地址:https://www.cnblogs.com/miao-study/p/11479801.html
Copyright © 2011-2022 走看看