1typedef struct node{
2 int value; //this is the value the node stores
3 struct node *next; //this is the node the current node points to. this is how the nodes link
4}node;
5
6node *createNode(int val){
7 node *newNode = malloc(sizeof(node));
8 newNode->value = val;
9 newNode->next = NULL;
10 return newNode;
11}
1public class LinkedList {
2
3 private Node head;
4 private int length = 0;
5
6 public LinkedList() {
7 this.head = new Node(null);
8 }
9
10 public int size() {
11 return length;
12 }
13
14
15 // Adds an element to the end of the list
16 public void add(Object data) {
17
18 Node node = new Node(data);
19 Node iterator = head;
20 while (iterator.getNext() != null){
21 iterator = iterator.getNext();
22 }
23 iterator.setNext(node);
24 length++;
25 }
26
27
28 // Obtains an element by index
29 public Object get(int index) {
30
31 if (head.getNext() == null || index >= length){
32 return null;
33 }
34
35 Node iterator = head.getNext();
36 int counter = 0;
37
38 while(counter < index){
39
40 iterator = iterator.getNext();
41 counter++;
42 }
43 return iterator.getData();
44
45 }
46
47
48 // Returns the index of the element in the list
49 public int indexOf(Object data) {
50 Node obj=head;
51 for (int i = 0; i < length; i++) {
52 obj = obj.getNext();
53 if (obj.getData().equals(data)) {
54 return i;
55 }
56 }
57 return -1;
58 //throw new Exception("Data not found");
59 }
60
61
62 // Removes an element from the list
63 public boolean remove(Object data) {
64
65 if (head.getNext() == null){
66 return false;
67 }
68
69 Node iterator = head;
70
71 while(iterator.getNext() != null){
72
73 if (iterator.getNext().getData().equals(data)){
74 iterator.setNext(iterator.getNext().getNext());
75 length--;
76 return true;
77 }
78
79 iterator = iterator.getNext();
80 }
81
82 return false;
83 }
84
85 private class Node {
86
87 private Object data;
88 private Node next;
89
90 public Node(Object data) {
91 this.data = data;
92 next = null;
93 }
94
95 public Object getData() {
96 return data;
97 }
98
99 public void setData(Object data) {
100 this.data = data;
101 }
102
103 public Node getNext() {
104 return next;
105 }
106
107 public void setNext(Node next) {
108 this.next = next;
109 }
110 }
111
112}
1import java.util.LinkedList;
2LinkedList<Integer> myList = new LinkedList<Integer>();
3myList.add(0);
4myList.remove(0);//Remove at index 0
5myList.size();
6myList.get(0);//Return element at index 0