2.3 Implement an algorithm to delete a node in the middle of a singly linked list, given only access to that node.
public static boolean deleteNode(LinkedListNode n){
if(!n || !n->next) return false;
n.data = n.next.data;
n.next = n.next.next;
return true;
}
2.4 Write code to partition a linked list around a value x, such that all nodes less than x
come before alt nodes greater than or equal to x.
public LinkedListNode partition(LinkedListNode node, int x){
LinkedListNode index = node, cur = node;
while(cur){
if(cur.data < x){
int temp = cur.data;
cur.data = index.data;
index.data = temp;
index = index.next;
}
cur = cur.next;
}
return node;
}
No comments:
Post a Comment