标签:
给出一个链表,每个节点包含一个额外增加的随机指针可以指向链表中的任何节点或空的节点。
返回一个深拷贝的链表。
# Definition for singly-linked list with a random pointer. # class RandomListNode: # def __init__(self, x): # self.label = x # self.next = None # self.random = None class Solution: # @param head: A RandomListNode # @return: A RandomListNode def copyRandomList(self, head): # write your code here if head is None: return None p = head while p is not None: r = p.next node = RandomListNode(p.label) node.next = p.next p.next = node p = r p = head q = p.next if q is None: print("None") while p is not None and q is not None: if p.random is not None: q.random = p.random.next p = q.next if p is not None: q = p.next ret = head.next del head q = ret while q.next is not None: p = q.next q.next = p.next del p q = q.next return ret
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: /** * @param head: The head of linked list with a random pointer. * @return: A new head of a deep copy of the list. */ RandomListNode *copyRandomList(RandomListNode *head) { // write your code here if(head == NULL) { return NULL; }//if RandomListNode *p = head; while(p != NULL) { RandomListNode *r = p->next; RandomListNode *tmp = new RandomListNode(p->label); tmp->next = p->next; p->next = tmp; p = r; }//while p = head; RandomListNode *q = head->next; while(p && q) { if(p->random) { q->random = p->random->next; } p = q->next; if(p) { q = p->next; } }//while RandomListNode *ret = head->next; delete head; q = ret; while(q->next) { p = q->next; q->next = p->next; delete p; q = q->next; }//while return ret; } };
标签:
原文地址:http://blog.csdn.net/fly_yr/article/details/51606843