面经:复制多指针链表

主题:面经

Question:

Given a list of nodes , Node class has fields value(of type integer) , next(of type Node) , other(of type Node) where next points to next node and other points to some arbitrary node in the list. Make a copy of the list. Describe an efficient algorithm and implement it. 


分析:

利用HashMap<Node, Integer>给原始链表的每个节点编号。

遍历原始链表,按照next指针复制出一个新的链表,同时在这次的遍历过程中,给所有节点制造一个编号并放入hashmap中。

接下来,建立two pointers,分别指向原始链表和新建链表表头。遍历原始链表,找到节点的other指针的编号,根据编号,遍历新建链表并得到other指针的位置,完成指向操作。

遍历完成后,得解。


代码:

import java.util.*;

class Test{
    public static void main(String[] args){
		Node a1 = new Node(1);
		Node a2 = new Node(2);
		Node a3 = new Node(3);
		Node a4 = new Node(4);
		Node a5 = new Node(5);
		a1.next = a2;
		a2.next = a3;
		a3.next = a4;
		a4.next = a5;
		a1.other = a3;
		a2.other = a1;
		a3.other = a5;
		a4.other = a3;
		a5.other = a4;
		
		Solution sol = new Solution();
		Node b1 = sol.copyList(a1);
		Node b2 = b1.next;
		Node b3 = b2.next;
		Node b4 = b3.next;
		Node b5 = b4.next;
		System.out.println(b3.other.val);
		System.out.println(a3.other.val);
		System.out.println(a3.other);
		System.out.println(b3.other);
	}
}

class Solution{
	public Node copyList(Node a){
		Node start = new Node(0);
		Node pre = start, cur = a;
		int cnt = 0;
		HashMap<Node, Integer> hm = new HashMap<Node, Integer>();
		while(cur != null){
			Node x = new Node(cur.val);
			hm.put(cur, cnt);
			pre.next = x;
			pre = pre.next;
			cur = cur.next;
			cnt++;
		}
		
		Node aI = a, bI = start.next;
		while(aI != null){
			if(aI.other != null){
				int num = hm.get(aI.other);
				Node x = getOther(num, start.next);
				bI.other = x;
			}
			aI = aI.next;
			bI = bI.next;
		}
		return start.next;
	}
	private Node getOther(int num, Node head){
		Node cur = head;
		for(int i=0; i<num; i++)
			cur = cur.next;
		return cur;
	}
}

class Node{
	int val;
	Node next;
	Node other;
	Node(int val){
		this.val = val;
		next = null;
		other = null;
	}
}

总结:

HashMap的巧妙应用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值