-
-
Save gaoyike/9088a0cc8d2d6af7694f to your computer and use it in GitHub Desktop.
2.3
This file contains 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
/** | |
* 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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Never write something like (fast.next != null && fast.next.next != null) in the program. It will cause NPE in some cases.