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)

運行結果:



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM