中文english
在鍊錶中插入乙個節點。
樣例 1:
輸入:head = 1->4->6->8->null, val = 5
輸出:1->4->5->6->8->null
樣例 2:
輸入:head = 1->null, val = 2
輸出:1->2->null
第乙個版本:
"""definition of listnode
class listnode(object
): def __init__(self, val, next=none):
self.val =val
self.next =next
"""class
solution:
"""@param head: the head of linked list.
@param val: an integer.
@return: the head of
newlinked list.
"""def insertnode(self, head, val):
# write your code here
new_node =listnode(val)
#邊界情況
if not head: return
none
if head.val >=val:
new_node.next =head
return
new_node
p =head
while
p.next:
#如果在中間的話,則直接返回
if val > p.val and val <=p.next.val:
new_node.next =p.next
p.next =new_node
return
head
else
: p =p.next
else
: #如果不在中間
p.next =new_node
return
head
第二個版本:
"""definition of listnode
class listnode(object
): def __init__(self, val, next=none):
self.val =val
self.next =next
"""class
solution:
"""@param head: the head of linked list.
@param val: an integer.
@return: the head of
newlinked list.
"""def insertnode(self, head, val):
# write your code here
#一直到val
dummy = listnode(0
) dummy.next =head
p =dummy
while p.next and val p =p.next
#開始拼接
new_node =listnode(val, p.next)
p.next =new_node
return head
向公升序單向鍊錶中插入乙個節點
詳細描述 原型 listnode insertnodetolist listnode plisthead,listnode pinsertnode 輸入引數 listnode plisthead 單向鍊錶 listnode pinsertnode 新插入節點 輸出引數 指標指向的記憶體區域保證有效 ...
鍊錶中新增乙個節點和刪除乙個節點
這裡主要記錄單向列表新增和刪除乙個指定位置節點的書寫方法。首先先建立鍊錶節點資料的基本型別 ifndef node h define node h include person.h class node endif node h 接下來建立節點的節本型別 class list endif 往指定節點...
鍊錶中插入乙個節點的三種情況
在鍊錶中插入乙個元素可以分為三種情況 1 在節點的時候 2 在鍊錶中間的任意位置 3 在鍊錶的最後位置,也可以認為這種情況為追加 這個就留到追加的時候來實現 下面是 的實現 sn insert s node sn head 傳入的引數是被插入鍊錶中的頭指標 sn insert node null,d...