Last active
September 27, 2019 04:12
-
-
Save abhinavjonnada82/2989b11a0bb585ef3542c0ea075ca322 to your computer and use it in GitHub Desktop.
Linked List - LeetCode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # cycle in a inked lists | |
| def hasCycle(self, head: ListNode) -> bool: | |
| first = head | |
| second = head | |
| while first and second and second.next: # Important takes care of edge cases | |
| first = first.next | |
| second = second.next.next | |
| if first == second: | |
| return True | |
| return False | |
| # intersection of two singly linked lists | |
| def getIntersectionNode(self, headA, headB): | |
| curA,curB = headA,headB | |
| lenA,lenB = 0,0 | |
| while curA is not None: | |
| lenA += 1 | |
| curA = curA.next | |
| while curB is not None: | |
| lenB += 1 | |
| curB = curB.next | |
| curA,curB = headA,headB # reassign value | |
| if lenA > lenB: | |
| for i in range(lenA-lenB): | |
| curA = curA.next | |
| elif lenB > lenA: | |
| for i in range(lenB-lenA): | |
| curB = curB.next | |
| while curB != curA: | |
| curB = curB.next | |
| curA = curA.next | |
| return curA | |
| # Delete Duplicate nodes in a Linked List | |
| def deleteDuplicates(self, head: ListNode) -> ListNode: | |
| cur = head | |
| while cur and cur.next: | |
| if cur.val == cur.next.val: | |
| cur.next = cur.next.next # setting duplicate node value equal to new one | |
| else: | |
| cur = cur.next | |
| return head | |
| # Palindrome | |
| def isPalindrome(head): | |
| cur, fast, slow = head | |
| # Get the midoint using slow | |
| while fast and fast.next: | |
| fast = fast.next.next | |
| slow = slow.next | |
| stack = [slow.val] | |
| # Push the second half into the stack | |
| while slow: | |
| slow = slow.next | |
| stack.append(slow.val) | |
| # Compare | |
| while stack: | |
| if stack.pop == cur.val: | |
| cur = cur.next | |
| else: | |
| return False | |
| return True | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment