JAVA链表测试代码

测试模板
class ListNode { // 链表类
	int val;
	ListNode next = null;

	public ListNode(int val) {
		this.val = val;
	}
}

class Solution {

	public static void Myprint(ListNode t1) // 输出链表
	{
		while (t1 != null) {
			System.out.println(t1.val);
			t1 = t1.next;
		}
	}

	//这里可写相关操作函数

	public static void main(String[] args) {
		ListNode t1 = new ListNode(1);
		ListNode t2 = new ListNode(2);
		ListNode t3 = new ListNode(3);
		ListNode t4 = new ListNode(4);
		ListNode t5 = new ListNode(5);

		t1.next = t2;
		t2.next = null;
		System.out.println("--------链表t1-------");
		Myprint(t1);
		
		t3.next = t4;
		t4.next = t5;
		t5.next = null;
		System.out.println("--------链表t3-------");
		Myprint(t3);
		
		//相关操作函数
	}
}
例子:合并两个排序的链表
class ListNode { // 链表类
	int val;
	ListNode next = null;

	public ListNode(int val) {
		this.val = val;
	}
}

class Solution {

	public static void Myprint(ListNode t1) // 输出链表
	{
		while (t1 != null) {
			System.out.println(t1.val);
			t1 = t1.next;
		}
	}

	public static ListNode Merge(ListNode list1, ListNode list2) { // 两个链表的归并排序
		// 归并排序的思想
		if (list1 == null) {
			return list2;
		}
		if (list2 == null) {
			return list1;
		}
		ListNode head = new ListNode(-1);
		ListNode list3 = head;
		while (list1 != null && list2 != null) {
			if (list1.val < list2.val) {
				list3.next = list1;
				list1 = list1.next;
			} else {
				list3.next = list2;
				list2 = list2.next;
			}
			list3 = list3.next;
		}

		while (list1 != null) {
			list3.next = list1;
			list1 = list1.next;
			list3 = list3.next;
		}

		while (list2 != null) {
			list3.next = list2;
			list2 = list2.next;
			list3 = list3.next;
		}
		return head.next;
	}

	public static void main(String[] args) {
		ListNode t1 = new ListNode(1);
		ListNode t2 = new ListNode(2);
		ListNode t3 = new ListNode(3);
		ListNode t4 = new ListNode(4);
		ListNode t5 = new ListNode(5);

		t1.next = t2;
		t2.next = null;
		System.out.println("--------链表t1-------");
		Myprint(t1);
		
		t3.next = t4;
		t4.next = t5;
		t5.next = null;
		System.out.println("--------链表t3-------");
		Myprint(t3);
		
		System.out.println("--------t1与t3合并的链表-------");
		ListNode r = Merge(t1, t3);
		Myprint(r);
	}
}

全部评论

相关推荐

“校招”、“3-5年经验”
xiaolihuamao:逆向工程不是搞外挂的吗,好像现在大学生坐牢最多的就是诈骗罪和非法侵入计算机系统罪,发美金,还居家办公,就是怕被一锅端,
点赞 评论 收藏
分享
水墨不写bug:疑似没有上过大学
点赞 评论 收藏
分享
king122:专业技能不要写这么多,熟悉和熟练你经不住问,排版有些难看,中间的空隙搞小一点,项目描述的话感觉是从课程中抄下来的,改一改吧,不然烂大街了,每个项目都写一两点,用什么技术实现了什么难点,然后再写一些数字上去像时间又花了90%这样,这样面试会多一些,如果觉得自己的项目还是不够用的话,我有几个大厂最近做过的实习项目,感兴趣的话可以看我简介中的项目地址
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务