1. Duplicate a linked list

半世苍凉 提交于 2019-11-29 16:04:58

题目

Write a function duplicate(head) to duplicate the linked list. Here head is the id of the head node of a linked list.
Example: For linked list 0 -> 1 -> 2, modify the linked list (in-place) into 0 -> 1 -> 2 -> 0 -> 1 -> 2.

代码

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

def duplicate(head):
    if head==None:
        return None
    temp = newhead = ListNode(0)
    head1 = head
    while head1 != None:
        temp.data = head1.data
        head1 = head1.next
        temp.next = ListNode(0)
        temp = temp.next
    temp.next = head.next #magic step...
    return newhead

def printlistnode(head):
    while head!=None:
        print(head.data)
        head=head.next

def main():
    head = ListNode(0)
    node1 = ListNode(1)
    node2 = ListNode(2)
    head.next = node1
    node1.next = node2
    newhead = duplicate(head)
    printlistnode(newhead)

main()

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!