#!/usr/bin/env python
# encoding: utf-8
'''
Python程序员面试算法宝典---解题总结: 第1章 链表 1.7 如何把链表相邻元素翻转
题目:
把链表相邻元素翻转,例如给定链表为 1->2->3->4->5->6->7,则翻转后的链表变为
2->1->4->3->6->5->7
分析:
可以设定previous, current, next3个指针,分别指向当前结点的前一个结点,
当前结点,下一个节点,然后令:
previous.nextNode = next
current.nextNode = previous
接下来遍历下一个待翻转的结点对:
current = next.nextNode
next = current.nextNode if current else None
previous = next
有以下几种情况:
1 previous为空
无需翻转,直接结束处理
2 current为空
无需翻转,直接结束处理
3 next为空
翻转
关键:
1 必须保存上一组结点交换后指针,指向下一组交换后的结点
# 注意,还必须保存上一组结点交换后指针,指向下一组交换后的结点
prevPrev = None
while current:
previous.nextNode = next
current.nextNode = previous
if prevPrev:
prevPrev.nextNode = current
# 注意,要获取新的头结点
if isFirst:
isFirst = False
newHead = current
prevPrev = previous
previous = next
current = next.nextNode if next else None
next = current.nextNode if current else None
参考:
Python程序员面试算法宝典
'''
def swapNeighbour(head):
if not head:
return head
if not head.nextNode:
return head
previous = head
current = previous.nextNode
next = current.nextNode
isFirst = True
newHead = None
# 注意,还必须上一组结点交换后指针,指向下一组交换后的结点
prevPrev = None
while current:
previous.nextNode = next
current.nextNode = previous
if prevPrev:
prevPrev.nextNode = current
# 注意,要获取新的头结点
if isFirst:
isFirst = False
newHead = current
prevPrev = previous
previous = next
current = next.nextNode if next else None
next = current.nextNode if current else None
return newHead
class Node(object):
def __init__(self, data=None, nextNode=None):
self.data = data
self.nextNode = nextNode
def buildList(arr):
if not arr:
return
head = Node(arr[0])
current = head
for i, data in enumerate(arr):
if 0 == i:
continue
newNode = Node(data)
current.nextNode = newNode
current = newNode
return head
def printList(head):
if not head:
return
current = head
result = ""
while current:
if result:
result += "->" + str(current.data)
else:
result += str(current.data)
current = current.nextNode
print result
def process():
for num in range(8, 0, -1):
arr = [i for i in range(1, num)]
head = buildList(arr)
head = swapNeighbour(head)
printList(head)
arr = None
head = buildList(arr)
head = swapNeighbour(head)
printList(head)
if __name__ == "__main__":
process()