求有环链表环的起点

求有环链表环的起点

可设快慢两个指针,当慢指针走一步时,快指针走两步。假设头节点距离环起点有k步,则当慢指针p1走到环起点时,慢指针p1与快指针p2相距k布,若环长度为l,此时看成p2追赶p1则p2与p1相距l-k步数,从此时开始当p1走l-k步时p1与p2相遇,此时在定义一个指向头节点的指针p,p与p1同时向前走,两者相遇点即为环的起点。

class ListNode{
	Object val;
	ListNode next;
	public ListNode(Object val) {
		this.val=val;
	}
	@Override
	public String toString() {
		StringBuilder sb=new StringBuilder();
		ListNode p=next;
		while(p!=null) {
			sb.append(p.val);
			p=p.next;
		}
		return sb.toString();
	}
}
public class BeginOfCircle{
	public static ListNode beginOfCircle(ListNode head) {
		ListNode p1=head;
		ListNode p2=head;
		while(p1!=null&&p1.next!=null) {
			p1=p1.next;
			p2=p2.next.next;
			if(p1==p2)break;			
		}
		//if(p1!=null||p2!=null)return null;
		ListNode p=head;
		while(p!=p1) {//相遇点即为环起点
			p=p.next;
		}
		return p;
	}
	public static void main(String[] args) {
		ListNode node=new ListNode(1);
		node.next=new ListNode(2);
		node.next.next=new ListNode(32);
		node.next.next.next=new ListNode(32);
		node.next.next.next.next=new ListNode(2);
		node.next.next.next.next.next=node.next;
		System.out.println(beginOfCircle(node).val);//结果应为2
	}
}
在Python,我们可以使用快慢指针(Floyd's Tortoise and Hare Algorithm 或者叫Cycle Detection Algorithm)来解决这个问题。首先,我们需要创建链表节点,并实现链表的相关操作,如插入节点、判断是否有等。然后,我们定义两个指针,初始都指向链表头部,其一个速度较快(每一步走两步),另一个速度较慢(每一步走一步)。如果链表,那么这两个指针最终会相遇;如果没有,快指针将先到达链表的末尾。 下面是伪代码示例: ```python class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def generate_linked_list_with_loop(n, has_loop): # 创建链表 head = ListNode(1) cur = head for _ in range(n - 1): if has_loop: new_node = ListNode(0, cur) # 如果有,新节点连接到当前节点 else: new_node = ListNode(0) cur.next = new_node cur = new_node # 添加循 if has_loop: cur.next = head # 使得最后两个节点形成 return head # 判断的长度 def detect_cycle_length(head): slow = fast = head while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: # 找到了 cycle_len = 1 p = slow while p != fast: p = p.next fast = fast.next cycle_len += 1 return cycle_len return 0 # 没有 # 示例 head1 = generate_linked_list_with_loop(5, True) # 随机生成带链表 head2 = generate_linked_list_with_loop(4, False) # 随机生成无链表 length1 = detect_cycle_length(head1) length2 = detect_cycle_length(head2) if length1 > 0: print(f"链表1的长度是 {length1},头结点为 {head1}") elif length1 == 0: print("链表1无") else: print("无法获取链表1的状态") if length2 > 0: print(f"链表2的长度是 {length2},头结点为 {head2}") elif length2 == 0: print("链表2无") else: print("无法获取链表2的状态")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹏之翼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值