鏈表的操作

鏈表的建立:

首先建立節點:

class ListNode():
    def __init__(self,value):
        self.val=value
        self.next=None

建立鏈表:

def createList(num):
    if num<=0:
        return None
    head=None
    val=0
    node=None
    while num>0:
        if head is None:
            head=ListNode(val)   #爲了保存head頭節點的位置不變化
            node=head
        else:
            node.next=ListNode(val)
            node=node.next
        val+=1
        num-=1
    return head

head=createList(5)
while head is not None:
    print("{0}->".format(head.val),end=' ')
    head=head.next

 

給定一個鏈表,旋轉鏈表,將鏈表每個節點向右移動 k 個位置,其中 k 是非負數。

輸入: 1->2->3->4->5->NULL, k = 2

輸出: 4->5->1->2->3->NULL

解釋: 向右旋轉 1 步: 5->1->2->3->4->NULL

         向右旋轉 2 步: 4->5->1->2->3->NULL

 

思路:第一步建立節點。 第二步建立鏈表。  第三步,建立旋轉函數。

旋轉函數的思路爲:將一個鏈表首尾相連。然後判斷需要挪動的位置。把頭指針放到挪動後的位置。這個時候需要注意的是,此時的鏈表仍然是首尾相連的。應該從頭節點指針位置的地方斷開。

 

class ListNode():
    def __init__(self,value):
        self.val=value
        self.next=None

#可以考慮先把鏈表變成一個環形
def xuanzhuan(head,K):
    p=head
    count=1
    while p.next !=None:
        p=p.next
        count+=1
    p.next=head
    K%=count #移動的位數
    for i in range(count-K-1):
        head=head.next
    #斷開
    p=head
    head=head.next
    p.next=None
    return head

def createList(num):
    if num<=0:
        return None
    head=None
    # val=0
    val=1
    node=None
    while num>0:
        if head is None:
            head=ListNode(val)   #爲了保存head頭節點的位置不變化
            node=head
        else:
            node.next=ListNode(val)
            node=node.next
        val+=1
        num-=1
    return head

head=createList(5)
p=head
while p is not None:
    print("{0}->".format(p.val),end=' ')
    p=p.next
print()

head=xuanzhuan(head,2)
while head is not None:
    print("{0}->".format(head.val),end=' ')
    head=head.next

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章