//点击标题可以到达题目的地址。
1、给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null
public class LinkedList { public LinkedNode head; public LinkedNode detectCycle() { LinkedNode fast = this.head; LinkedNode slow = this.head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { break; } } if (fast == null || fast.next == null) { return null; } fast = this.head; while (fast != slow) { fast = fast.next; slow = slow.next; } return slow; } }
public class LinkedList { public LinkedNode head; public boolean hasCycle() { if (this.head == null) { return false; } LinkedNode fast = this.head; LinkedNode slow = this.head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; if (fast == slow) { return true; } } return false; } }
public class Test{//这里的公共节点指的是地址 public static LinkedNode getIntersectionNode(LinkedNode headA, LinkedNode headB) { LinkedNode pl = headA; LinkedNode ps = headB; int lenA = 0; while (pl != null) { lenA ++; pl = pl.next; } int lenB = 0; while (ps != null) { lenB ++; ps = ps.next; } pl = headA; ps = headB; int len = lenA - lenB; if (len < 0) { pl = headB; ps = headA; len = lenB - lenA; } while (len != 0) { pl = pl.next; len--; } while (pl != null && ps != null && pl != ps ) { pl = pl.next; ps = ps.next; } if (pl != null && pl == ps) { return pl; } return null; }
}
public class LinkedList { public LinkedNode head; public boolean chkPalindrome() { if (this.head == null) { return true; } LinkedNode fast = this.head; LinkedNode slow = this.head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } LinkedNode cur = slow.next; while (cur != null) { LinkedNode curNext = cur.next; cur.next = slow; slow = cur; cur = curNext; } while (this.head != slow) { if (this.head.val != slow.val) { return false; } if (this.head.next == slow) { return true; } this.head = this.head.next; slow = slow.next; } return true; } }
5、在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针
public class LinkedList { public LinkedNode head; public LinkedNode deleteDuplication() { LinkedNode newHead = new LinkedNode(-1); LinkedNode tmp = newHead; LinkedNode cur = this.head; while(cur != null) { if (cur.next != null && cur.val == cur.next.val) { while (cur.next != null && cur.val == cur.next.val) { cur = cur.next; } cur = cur.next; } else { tmp.next = cur; tmp = tmp.next; cur = cur.next; } } tmp.next = null; return newHead.next; } }