147 對鍊錶進行插入排序 PYTHON

2021-10-01 16:10:40 字數 3310 閱讀 3626

"""#設立頭結點

head_ = listnode(-1

) tail = head_

p = head

while p:

#拆下單個節點

tmp_node = deepcopy(p)

tmp_node.

next

=none

print

(tmp_node)

print

(head_)

if head_.

next

!=none

: flag =

false

pre_c = head_

c = head_.

next

while c:

print(1

)if tmp_node.val <= c.val:

tmp_node.

next

= c pre_c.

next

= tmp_node

flag =

true

p = p.

next

break

else

: c = c.

next

pre_c = pre_c.

next

ifnot flag:

tail.

next

= tmp_node

tail = tail.

next

p = p.

next

else

: head_.

next

= tmp_node

tail = head_.

next

p = p.

next

return head_.

next

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

from copy import deepcopy

class

solution

(object):

definsertionsortlist

(self, head)

:"""

:type head: listnode

:rtype: listnode

"""res = listnode(-1

) p = head

while p:

next

= p.

next

res.

next

= self.insert(res.

next

,p) p =

next

return res.

next

definsert

(self,head,node):if

not head or head.val >node.val:

node.

next

= head

return node

head.

next

= self.insert(head.

next

, node)

return head

# definition for singly-linked list.

# class listnode(object):

# def __init__(self, x):

# self.val = x

# self.next = none

from copy import deepcopy

class

solution

(object):

definsertionsortlist

(self, head)

:"""

:type head: listnode

:rtype: listnode

"""ifnot head:

return

none

head_ = listnode(-1

)#新增表頭節點

head_.

next

= head

p = head.

next

#保留當前節點的第乙個節點,用於比較

head.

next

=none

while p:

curr = p.

next

#儲存下乙個節點資訊

q = head_ #設立頭結點指標

while q.

next

and q.

next

.val <= p.val:

#一直迴圈找比當前頭結點值小的節點

q = q.

next

p.next

= q.

next

#頭插法插入節點

q.next

= p p = curr #後移

return head_.

next

147 對鍊錶進行插入排序

對鍊錶進行插入排序。插入排序的動畫演示如上。從第乙個元素開始,該鍊錶可以被認為已經部分排序 用黑色表示 每次迭代時,從輸入資料中移除乙個元素 用紅色表示 並原地將其插入到已排好序的鍊錶中。definition for singly linked list.public class listnode ...

147 對鍊錶進行插入排序

難度 中等 題目描述 思路總結 為什麼鍊錶題中等難度的都能做出來,而其它型別的題不行呢,值得思考。題解一 class solution def insertionsortlist self,head listnode listnode dummy listnode 0 while head cur ...

147 對鍊錶進行插入排序

第一次嘗試 對鍊錶進行插入排序。鍊錶為無頭結點 單向 不迴圈。由於涉及到結構體,所以寫不了完整的測試 下面展示的 為leetcode中寫的 leetcode鏈結 struct listnode insertionsortlist struct listnode head 設定虛頭結點 struct ...