链表的反转、合并(不借助额外list数组)

链表的基本操作:线性表 (单链表、循环链表-python实现)

反转链表:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:

    def __init__(self,list):
        self.head=ListNode(None)
        self.list=list

    def listCreateForward(self):
        temp = self.head
        while self.list:
            num = self.list.pop(0)
            node = ListNode(num)
            temp.next = node
            temp = node
        self.readList(self.head)
        self.ReverseList(self.head)

    def ReverseList(self, pHead):
        if pHead.next==None:
            return pHead
        head=ListNode(None)
        while pHead.next.next!=None:
            temp = pHead.next
            pHead.next=pHead.next.next
            temp.next=head.next
            head.next=temp
        node=pHead.next
        node.next=head.next
        head.next=node
        self.readList(head)

    def readList(self,head):
        temp =head
        while temp.next != None:
            temp = temp.next
            print temp.val


s=Solution([1,2,3,4,5,6])
s.listCreateForward()

合并链表:

# -*- coding:utf-8 -*-
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:

    def __init__(self,list):
        self.head=ListNode(None)
        self.list=list

    def listCreateForward(self):
        temp = self.head
        while self.list:
            num = self.list.pop(0)
            node = ListNode(num)
            temp.next = node
            temp = node

    def readList(self,head):
        temp =head
        while temp.next != None:
            temp = temp.next
            print temp.val

    def Merge(self, pHead1, pHead2):
        if not pHead1.next and not pHead2.next:
            return
        elif not pHead1.next:
            return pHead2
        elif not pHead2.next:
            return pHead1
        flag=0
        temp=pHead1
        temp1=temp.next
        temp2=pHead2.next
        while True:

            while temp1.val<temp2.val:
                if temp1.next==None:
                    break
                temp=temp1
                temp1=temp.next

            node=temp2
            if temp2.next == None:
                flag=1
            else:
                temp2=temp2.next

            if temp1.next==None and temp1.val>node.val:
                node.next = temp1
                temp.next = node
                temp = temp.next
            elif temp1.next==None and temp1.val<node.val:
                node.next=None
                temp1.next=node
            else:
                node.next=temp1
                temp.next=node
                temp=temp.next
            if flag==1:
                break
        return pHead1


s1=Solution([1,3,6,8,99,123])
s1.listCreateForward()
s2=Solution([2,3,5,7,11,13,15,16,18])
s2.listCreateForward()
s1.readList(s1.Merge(s1.head,s2.head))
posted @ 2018-04-11 18:38  ybf&yyj  阅读(264)  评论(0编辑  收藏  举报