【DataStructure】Some useful methods about linkedList(二)

Method 1: Add one list into the other list.

For example, if list1is {22, 33, 44, 55} and  list2 is {66, 77, 88, 99},then append(list1, list2)will change list1to {22, 33, 44, 55, 44, 66, 77, 88, 99}.

static void append(Node list1, Node list2) {
		if (list1 == null) {
			throw new IllegalArgumentException();
		}
		while (list1.next != null) {
			list1 = list1.next;
		}
		list1.next = list2;
	}

The output is as follows:



Method2: Gets a new list combined by two list

For example, if list1 is {22, 33, 44, 55} and  list2 is {66, 77, 88, 99}, then concat(list1, list2)will return the new list {22, 33, 44, 55, 44, 55, 66, 77, 88}. 

Note that the three lists should be completely independent of each other. Changing one list should have no effect upon the others.

static Node concat(Node list1, Node list2) {
		Node list3 = new Node(0);
		Node p = list1;
		Node q = list3;
		while(p != null)
		{
			q.next = new Node(p.data);
			p = p.next;
			q = q.next;
		}
	    p = list2;
	    while(p != null)
	    {
	    	q.next = new Node(p.data);
	    	q = q.next;
	    	p = p.next;
	    }
		return list3.next;
	}

The output is as follows:


Method 3 : Replace the value of element number i with x

void set(Node list, int i, int x)

For example, if list is {22, 33, 44, 55, 66, 77, 88, 99}, then set(list, 2, 50) will change List to {22, 33, 50, 55, 66, 44, 88, 99}

Solution 1:
	static void set(Node list, int i, int x) {
		Node p = list;
		int count = 0;
		while (p != null) {
			if (count == i) {
				p.data = x;
				break;
			}
			p = p.next;
			count++;
		}
	}
Solution2:
	static void set(Node list, int i, int x) {
		if (i < 0) {
			throw new IllegalArgumentException();
		}
		for (int j = 0; j < i; j++) {
			if (list == null) {
				throw new IllegalStateException();
			}
			list = list.next;
		}
		list.data = x;
	}

The output is as follows:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值