写链表代码技巧:
- 技巧一:理解指针或引用的含义
- 技巧二:警惕指针丢失和内存泄漏
- 技巧三:利用哨兵简化实现难度
- 技巧四:重点留意边界条件处理
- 技巧五:举例画图,辅助思考
- 技巧六:多写多练,没有捷径
问题描述:给定一个链表,判断链表中是否有环
法①set集合去重:
代码:
public class HasCycle {
/**
* 给定一个链表,判断链表中是否有环
* @param head
* @return
*/
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new LinkedHashSet<> ();
while (head != null){
if (set.contains(head)){
return true;
}
set.add(head);
head = head.next;
}
return false;
}
public static void main(String[] args) {
ListNode head = new ListNode(3);
ListNode next = new ListNode(2);
ListNode next1 = new ListNode(0);
ListNode next2 = new ListNode(-4);
head.next = next;
next.next = next1;
next1.next = next2;
next2.next = next;
boolean b = new HasCycle().hasCycle(head);
System.out.println(b);
}
}
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
法②:快慢指针
代码:
public boolean hasCycle(ListNode head,int x) {
if (head == null || head.next == null){
return false;
}
ListNode slowPoint = head;
ListNode fastPoint = head.next;
while (fastPoint != null && fastPoint.next != null) {
if(slowPoint.equals(fastPoint)){
return true;
}
slowPoint = slowPoint.next;
fastPoint = fastPoint.next.next;
}
return false;
}