---
title: "[leetcode] Copy List with Random Pointer"
author: "ouqi"
date: "2013-10-14T16:28:06Z"
tags: []
categories: ["编程语言"]
slug: "leetcode-copy-list-with-random-pointer"
draft: false
lastmod: "2013-10-14T16:28:06Z"
id: 1956769
url: "https://ouqi.iteye.com/blog/1956769"
---

剑指offer上面的题目

代码：

```
 public RandomListNode copyRandomList(RandomListNode head) {
	        // Note: The Solution object is instantiated only once and is reused by each test case.
	        cloneNode(head);
	        cloneRandom(head);
	        return patitionClone(head);
	    }
	    public void cloneNode(RandomListNode head){
	        RandomListNode p = head;
	        RandomListNode r;
	        while(p!=null){
	            RandomListNode node = new RandomListNode(p.label);
	            r = p.next;
	            p.next = node;
	            node.next = r;
	            p = r;
	        }
	    }
	    
	    public void cloneRandom(RandomListNode head){
	        RandomListNode p = head;
	        RandomListNode clone;
	        while(p!=null){
	            clone = p.next;
	            if(p.random!=null) clone.random = p.random.next;
	            p = clone.next;
	        }
	    }
	    
	    public RandomListNode patitionClone(RandomListNode head){
	        if(head==null) return null;
	        RandomListNode cloneHead = head.next;
	        RandomListNode  p = head;
	        RandomListNode  q = cloneHead;
	        RandomListNode  r = head.next.next;
	        RandomListNode temp;
	       
	        while(r!=null){
	            p.next = r;
	            p = q;
	            q = r;
	            r = r.next;
	        }
	        p.next = null;//之前的错误都是这个啊，一定要记得呐。。
	        return cloneHead;

	    }
```