상세 컨텐츠

본문 제목

[Go] Linked List - Summary - Two-Pointer in Linked List from Java to Go

Go/Leet Code

by Gopythor 2022. 5. 1. 23:24

본문

728x90
반응형

Code

Java

// Initialize slow & fast pointers
ListNode slow = head;
ListNode fast = head;
/**
 * Change this condition to fit specific problem.
 * Attention: remember to avoid null-pointer error
 **/
while (slow != null && fast != null && fast.next != null) {
    slow = slow.next;           // move slow pointer one step each time
    fast = fast.next.next;      // move fast pointer two steps each time
    if (slow == fast) {         // change this condition to fit specific problem
        return true;
    }
}
return false;   // change return value to fit specific problem

Go

// Initialize slow & fast pointers
var slow *ListNode = head
var fast *ListNode = head
/**
* Change this condition to fit specific problem.
* Attention: remember to avoid null-pointer error
**/
for slow != nil && fast != nil && fast.Next != nil {
	slow = slow.Next		// move slow pointer one step each time
	fast = fast.Next.Next	// move fast pointer two steps each time
	if slow == fast {		 // change this condition to fit specific problem
		return true
	}
}
return false	// change return value to fit specific problem

 

728x90
반응형

관련글 더보기

댓글 영역