Python 实现通过指针实现链表翻转,链表奇偶下标交换,链表的冒泡排序

# -*- 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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值