Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sharunkumar/55c1d927506fcbe5325f1f8ca166f9af to your computer and use it in GitHub Desktop.
Save sharunkumar/55c1d927506fcbe5325f1f8ca166f9af to your computer and use it in GitHub Desktop.
Singly Linked Lists
class Solution {
public ListNode deleteMiddle(ListNode head) {
// Edge case: return nullptr if there is only one node.
if (head.next == null)
return null;
// Initialize two pointers, 'slow' and 'fast'.
ListNode slow = head, fast = head.next.next;
// Let 'fast' move forward by 2 nodes, 'slow' move forward by 1 node each step.
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// When 'fast' reaches the end, remove the next node of 'slow' and return 'head'.
slow.next = slow.next.next;
return head;
}
}
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> nodesInB = new HashSet<ListNode>();
while (headB != null) {
nodesInB.add(headB);
headB = headB.next;
}
while (headA != null) {
// if we find the node pointed to by headA,
// in our set containing nodes of B, then return the node
if (nodesInB.contains(headA)) {
return headA;
}
headA = headA.next;
}
return null;
}
}
class Solution {
public ListNode removeElements(ListNode head, int val) {
ListNode sentinel = new ListNode(0);
sentinel.next = head;
ListNode prev = sentinel, curr = head;
while (curr != null) {
if (curr.val == val) prev.next = curr.next;
else prev = curr;
curr = curr.next;
}
return sentinel.next;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment