题目
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()
来源:https://blog.csdn.net/weixin_45405128/article/details/100849401