Skip to content

Instantly share code, notes, and snippets.

@gaoyike
Created June 22, 2014 17:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaoyike/9088a0cc8d2d6af7694f to your computer and use it in GitHub Desktop.
Save gaoyike/9088a0cc8d2d6af7694f to your computer and use it in GitHub Desktop.
2.3
/**
* Created by Readman on 6/23/14.
*/
public class deleteMiddle {
/*
time n
space 1
* */
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
deleteMiddle(head);
while (head != null) {
System.out.print(head.val +" ");
head = head.next;
}
}
public static void deleteMiddle (ListNode head) {
ListNode slow = head;
ListNode fast = head.next; // use next or record previous node of slow.
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
slow.next = slow.next.next;
}
}
Copy link

ghost commented Jun 23, 2014

you misunderstood this problem's meaning. the input is the node which need to be deleted.

@Noahsark
Copy link

Noahsark commented Jul 9, 2014

Never write something like (fast.next != null && fast.next.next != null) in the program. It will cause NPE in some cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment