본문 바로가기

All Categories137

LeetCode. Linked List Cycle [Linked List] Problem: Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail con.. 2020. 6. 4.
LeetCode. Palindrome Linked List [Linked List] Problem: Given a singly linked list, determine if it is a palindrome. Example 1: Input: 1->2 Output: false Example 2: Input: 1->2->2->1 Output: true -Summary- 1. Find a middle node using two-pointer in the original Linked list. (Fast and Slow) 2. Create a reverse_node and reverse the second half of the original Linked List 3. Compare 1st and 2nd half of the Linked list, if everything matches ret.. 2020. 6. 4.
LeetCode. Merge Two Sorted Lists [Linked List] Problem: Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 -Summary- 1. Create a dummy and curr variables to track and merge the two lists. 2. Compare l1 and l2 value. 'curr' will connect to the less value. Update l1 or l2 depends on the res.. 2020. 6. 3.
LeetCode. Reverse Linked List [Linked List] Problem: Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL -Summary- 1. Keep track of current / prev (copy the original list in the curr and prev) 2. Update and move the head (original) 3. Return prev -Other iterative solution- # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = .. 2020. 6. 3.
LeetCode. Remove Nth Node From End of List [Linked List] Problem: Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. -Summary- 1. First, create two dummy variables pointing to the head and copied dummy. 2. Calculate the head length 3. Once we face the.. 2020. 6. 3.
LeetCode. Delete Node in a Linked List [Linked List] Problem: Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. Given linked list -- head = [4,5,1,9], which looks like following: Example 1: Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function. Example 2: Input: head =.. 2020. 6. 3.