Created
April 7, 2015 15:07
-
-
Save michaelniu/dfd225dbbe0c11de83cb to your computer and use it in GitHub Desktop.
cc150_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
package cc150; | |
/* | |
*2.3 Implement an algorithm to delete a node in the middle of a singly linked list, | |
given only access to that node. | |
EXAMPLE | |
Input: the node c from the linked list a->b->c->d->e | |
Result: nothing is returned, but the new linked list looks like a- >b- >d->e | |
Algorithm | |
set c.data = c.next.data and c.next= c.next .next | |
O(1) and O(1) | |
*/ | |
public class DeleteMiddleNode_2_3 { | |
public static void main(String[] args) { | |
SinglyListNode root = new SinglyListNode(); | |
root.data = 12; | |
SinglyListNode current = root; | |
SinglyListNode newNode = new SinglyListNode(); | |
newNode.data = 22; | |
current.next = newNode; | |
current = current.next; | |
newNode = new SinglyListNode(); | |
newNode.data = 25; | |
current.next = newNode; | |
current = current.next; | |
newNode = new SinglyListNode(); | |
newNode.data = 32; | |
current.next = newNode; | |
current = current.next; | |
newNode = new SinglyListNode(); | |
newNode.data = 52; | |
current.next = newNode; | |
newNode.data = 26; | |
current.next = newNode; | |
current = current.next; | |
newNode = new SinglyListNode(); | |
newNode.data = 62; | |
current.next = newNode; | |
current = current.next; | |
newNode = new SinglyListNode(); | |
newNode.data = 72; | |
current.next = newNode; | |
// lets set the middle of the node as the data = 32 | |
// | |
SinglyListNode midNode = root; | |
while(midNode.data!=32) | |
midNode = midNode.next; | |
deleteMidNode(midNode); | |
current = root; | |
while(current != null){ | |
System.out.println(current.data); | |
current = current.next; | |
} | |
} | |
private static void deleteMidNode(SinglyListNode midNode) { | |
if(midNode.next == null){ | |
midNode = null; | |
return; | |
} | |
midNode.data = midNode.next.data; | |
midNode.next= midNode.next.next; | |
} | |
} | |
class SinglyListNode { | |
int data; | |
SinglyListNode next; | |
public SinglyListNode() { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment