# -*- coding: utf-8 -*-
"""
Created on Mon Apr 24 13:34:08 2017
@author: Administrator
"""
class ListNode: #参生链表的类
def __init__(self, x):
self.val = x
self.next = None
def printList(head): #打印函数
while(head!=None):
print head.val
head = head.next
def reverse(root): #链表反转
p_next = None
while(root!=None):
p = root
root = root.next
p.next = p_next
p_next = p
return p_next
def exchange(root): #链表的奇偶下标交换
head = ListNode("head")
head.next = root
if(head.next==None or head.next.next==None):
return head.next
p = head
count = 0
while(p.next.next!=None): #对应结点交换的核心部分
if(count%2==0):
x = p.next
y = p.next.next
p.next = y
x.next = y.next
y.next = x
count +=1
p = p.next
return head.next
def bubble_sort(root):
head = ListNode("head") #为root加入一个头结点,因为算法从第二个结点开始排序
head.next = root
if(head.next==None or head.next.next==None):
return head.next
f = None #此处的f用于确定尾部的位置,由于冒泡排序每次循环都能将最大/最小放到链表的最末尾,因此f应当逐步向head靠近。
while(head.next.next!=f):
p = head
while(p.next.next!=f):
if(p.next.val<p.next.next.val):
x = p.next
y = p.next.next
p.next = y
x.next = y.next
y.next = x
p = p.next
f = p.next
return head.next
if __name__ == "__main__":
p = head = ListNode(-1)
for i in range(12): #初始化链表
head.next = ListNode(i)
head = head.next
head0 = bubble_sort(p.next)
printList(head0)
print
head1 = reverse(head0)
printList(head1)
print
head2 = exchange(head1)
printList(head2)
Python 实现通过指针实现链表翻转,链表奇偶下标交换,链表的冒泡排序
最新推荐文章于 2023-03-06 20:32:21 发布