Xem mẫu
- Cài đặt Linked List
// Dinh nghia mot node trong linked list
class ListNode
{
int data;
ListNode nextNode;
ListNode(int value)
{
this(value, null);
}
ListNode(int value, ListNode node)
{
data = value;
nextNode = node;
}
int getData() { return data; }
ListNode getNext() { return nextNode; }
} 7
- Cài đặt Linked List
// Dinh nghia lop LinkedList
public class LinkedList
{
private ListNode firstNode;
private ListNode lastNode;
public LinkedList()
{
firstNode = lastNode = null;
}
public void insertAtFront(int insertItem)
{
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
firstNode = new ListNode( insertItem, firstNode );
}
8
- Cài đặt Linked List
public void insertAtBack( int insertItem )
{
if ( isEmpty() )
firstNode = lastNode = new ListNode( insertItem );
else
lastNode = lastNode.nextNode = new ListNode( insertItem );
}
public int removeFromFront()
{
int removeItem = -1;
if ( ! isEmpty() ) {
removeItem = firstNode.data;
if ( firstNode == lastNode )
firstNode = lastNode = null;
else
firstNode = firstNode.nextNode;
}
return removeItem;
} 9
- Cài đặt Linked List
public int removeFromBack()
{
int removeItem = -1;
if ( ! isEmpty() )
{
removeItem = lastNode.data;
if ( firstNode == lastNode )
firstNode = lastNode = null;
else
{
ListNode current = firstNode;
while ( current.nextNode != lastNode )
current = current.nextNode;
lastNode = current;
current.nextNode = null;
}
}
return removeItem;
} 10
- Cài đặt Linked List
public boolean isEmpty()
{
return (firstNode == null);
}
public void print()
{
ListNode node = firstNode;
while (node != null)
{
System.out.print(node.data + " ");
node = node.nextNode;
}
System.out.println("\n");
}
}
11
- Mô tả insertAtFront
(a) firstNode
7 11
new ListNode
12
(b) firstNode
7 11
new ListNode
12
12
nguon tai.lieu . vn