Overview
Definition: | A linked list is a recursive data structure that is either empty(null) or a reference to a node having a generic item and a reference to a linked list. Algorithms, Fourth Edition |
---|
Implementation
Here is the node implementation of a singly linked list in Java.
/**
* The node implementation of a singly linked list. You can call
* {@link Node#add} to add new node to the end.
*
*/
public class Node {
Node mNext = null;
int mData;
// constructor to create a new node.
Node(int data) {
mData = data;
}
/**
* Append or add new node to the end of linked list.
*
* @param int the data of the node to be added.
*/
void add(int data) {
Node end = new Node(data);
Node n = this;
while (n.mNext != null) {
n = n.mNext;
}
n.mNext = end;
}
}
Creat and access linked list
/*
* Create a linked list
* 5 -> 3 -> 8
*
*/
Node head = new Node(5);
head.add(3);
head.add(8);
/*
* Access node
*/
head.mData // Node 5
head.mNext.mData // Node 3
head.mNext.mNext.mData // Node 8
Simplified
/*
* more simplified implementation
*/
class Node {
int mData;
Node mNext;
public Node(int data) {
mData = data;
mNext = null;
}
}
Operations
- Deleting a Node from a singly linked list
Node delNode(Node head, int nd) {
/*
* If the Node to be deleted is head, just move head.
*/
if(head.mData == nd) {
return head.mNext; // Move head
}
Node n = head;
while(n.mNext != null) {
if (n.mNext.mData = nd) {
n.mNext = n.mNext.mNext;
return head; // head didn't changed
}
n = n.mNext;
}
}
- Deleting duplicated Nodes from an unsorted singly linked list
a) Use a buffer
import java.util.Hashtable;
public static void delDupNodes(LinkedListNode n) {
Hashtable tab = new Hashtable();
LinkedListNode pre = null; // previous node
while(n != null) {
if(tab.containsKey(n.mData)) {
pre.mNext = n.mNext;
} else {
tab.put(n.mData, true);
pre = n;
}
n = n.mNext;
}
}
b) Without a buffer
[To be Continued]