数据结构与算法(JAVA版)6_4:常见面试题

一种特殊的单链表结点类描述如下:

class Node{
	int value;
	Node next;
	Node rand;
	Node(int v){
		value=v;
	}
}

rand指针是单链表结点结构中新增的指针,rand可能指向链表中的任意一个节点,也可能指向null,给定一个由Node节点类型组成的无环单链表的头结点head,请实现一个函数完成这个链表的复制,并返回复制的新链表的头结点。

package com.inspire.chapter6;

import java.util.HashMap;

public class Code04_CopyListWithRandom {

	public static class Node {
		public int value;
		public Node next;
		public Node rand;

		public Node(int v) {
			value = v;
		}
	}

	// 方法一:用HashMap解决
	public static Node copyListWithRand1(Node head) {
		HashMap<Node, Node> map = new HashMap<>();
		Node cur = head;
		while (cur != null) {
			map.put(cur, new Node(cur.value));
			cur = cur.next;
		}
		cur = head;
		while (cur != null) {
			// cur 老
			// map.get(cur) 新
			map.get(cur).next = map.get(cur.next);
			map.get(cur).rand = map.get(cur.rand);
			cur = cur.next;
		}
		return map.get(head);
	}

	public static void main(String[] args) {

	}

}

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