链表——写给面试的自己(二)

本文介绍了链表的基本操作方法,包括链表的反转、利用栈实现从尾到头打印链表、判断链表是否存在环及环中节点数量等。通过这些实用技巧提升数据结构处理能力。
// 反转链表 面试出现率最高
	public static LinkList reverseLinkList(LinkList list) {
		if (list == null || list.head == null || list.head.next == null) {
			return list;
		}
		Node current = list.head;// 旧链表的头结点
		Node next;// 用来保存下一下结点

		LinkList linkList = new LinkList();
		while (current != null) {
			next = current.next;

			current.next = linkList.head;// 关键代码
			linkList.head = current;// 关键代码

			current = next;
		}

		return linkList;
	}

	// 从尾到头打印单链表:利用栈的特性
	public static void printTailLinkList1(LinkList list) {
		if (list == null || list.head == null) {
			return;
		}
		Stack<Node> stack = new Stack<Node>();// 先进后出
		Node current = list.head;
		while (current != null) {
			stack.push(current);// push node
			current = current.next;
		}
		while (!stack.isEmpty()) {
			System.out.print(stack.pop() + "<===");// 弹出pop node
		}
	}

	// 方法:判断单链表是否有环
	public static boolean hasCycle(LinkList list) {
		if (list == null || list.head == null) {
			return false;
		}
		Node frist = list.head;
		Node second = list.head;
		while (second != null && frist != null && second.next != null) {
			frist = frist.next;
			second = second.next.next;
			if (frist == second) {
				return true;
			}
		}
		return false;
	}

	// 方法:判断单链表环中结点
	public static Node hasCycleNode(LinkList list) {
		if (list == null || list.head == null) {
			return null;
		}
		Node frist = list.head;
		Node second = list.head;
		while (second != null && frist != null && second.next != null) {
			frist = frist.next;
			second = second.next.next;
			if (frist == second) {
				return frist;
			}
		}
		return null;
	}

	// 方法:求单链表中环的长度
	public static int cycleLength(LinkList list) {
		Node node = hasCycleNode(list);
		if (node == null) {
			return 0;
		}
		int count = 1;
		Node current = node.next;
		while (current != null && node != current) {
			count++;
			current = current.next;
		}
		return count;
	}


转载于:https://my.oschina.net/u/2477353/blog/651575

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值