目录
快慢指针是一种常用的数据结构思想,主要用于解决链表中的问题。
该算法会使用两个移动速度不同的指针,一个快指针和一个慢指针。
主要逻辑:
代码实现:
- public ListNode FindKthToTail (ListNode pHead, int k) {
- ListNode fast = pHead;
- while(k > 0){
- if(fast == null){ //处理k值大于链表长度的问题;
- return null;
- }
- fast = fast.next;
- k--;
-
- }
- ListNode slow = pHead;
- while(fast != null){
- fast = fast.next;
- slow = slow.next;
- }
- return slow;
- }
主要逻辑:
代码实现:
- public class ListNode {
- int val;
- ListNode next = null;
- public ListNode(int val) {
- this.val = val;
- }
- }
- public boolean isPail (ListNode head) {
- if (head == null) {
- return true;
- }
-
- //设置快慢两个指针;
- ListNode fast = head;
- ListNode slow = head;
- while(fast != null && fast.next != null){
- fast = fast.next.next;
- slow = slow.next;
- } //走完这个循环,slow指向中间节点;
-
- fast = head; //重新获得头节点;
- slow = reverse(slow); //逆序链表后半段;
-
- //两个指针同时走,直到slow为空;
- while(slow != null){
- //出现值不同,则直接返回false;
- if(fast.val != slow.val){
- return false;
-
- }
- fast = fast.next;
- slow = slow.next;
- }
-
- return true;
- }
- private ListNode reverse(ListNode cur) {
- ListNode prev = null;
- while(cur != null){
- ListNode curNext = cur.next;
- cur.next = prev;
- prev = cur;
- cur = curNext;
- }
- return prev;
- }
主要逻辑:
代码实现:
- public boolean hasCycle(ListNode head) {
- if(head == null){
- return false;
- }
- ListNode fast = head;
- ListNode slow = head;
- while(fast != null && fast.next != null){
- slow = slow.next;
- fast = fast.next.next;
- if(fast == slow){
- return true;
- }
- }
- return false;
- }
主要逻辑:
代码实现:
- public ListNode detectCycle(ListNode head) {
- if (head == null) {
- return null;
- }
-
- ListNode fast = head;
- ListNode slow = head;
-
- while(fast != null && fast.next != null){
- fast = fast.next.next;
- slow = slow.next;
- if(fast == slow){
- slow = head;
- while(true){
- if(fast == slow){
- return fast;
- }
- fast = fast.next;
- slow = slow.next;
- }
- }
- }
- return null;
- }
( 哈哈哈~~ 文章结束!)
( 看到这里,如果有为各位帅哥美女提供一点点灵感,请点一个小小的赞哦,比心💖💖💖 )