Hi Folks ,
Please find below the implementation of Singly Linked List from scratch in Java.
This is my way of implementing it , if you found any errors or improvements , i am welcome to any comments .
package LinkedListImpl;
public class Link {
Integer data;
Link link;
public Link(Integer data) {
this.data = data;
}
public Link() {
}
public void addFirst(Integer data) {
int tempData = this.data;
Link next = this.link;
this.data = data;
Link newLink = new Link(tempData);
this.link = newLink;
newLink.link = next;
}
public void add(Integer index, Integer data) {
if (this.data == null) {
this.data = data;
} else {
Link prev = this;
while (index != 1) {
prev = prev.link;
index--;
}
int tempData = prev.data;
Link rest = prev.link;
prev.data = data;
Link newLink = new Link(tempData);
prev.link = newLink;
newLink.link = rest;
}
}
public void addLast(Integer data) {
if (this.data == null) {
this.data = data;
} else {
Link prev = this;
while (prev != null && prev.link != null) {
prev = prev.link;
}
Link newLink = new Link(data);
prev.link = newLink;
}
}
public boolean contains(Integer data) {
Link cur = this;
while (cur != null) {
if (cur.data == data) {
return true;
}
cur = cur.link;
}
return false;
}
public void set(Integer index, Integer data) {
Link cur = this;
int cnt = 1;
while (cnt != index) {
cur = cur.link;
cnt++;
}
cur.data = data;
}
public Integer getFirst() {
return this.data;
}
public Integer get(Integer index) {
Link cur = this;
int cnt = 1;
while (cnt != index) {
cur = cur.link;
cnt++;
}
return cur.data;
}
public Integer getLast() {
Link cur = this;
while (cur.link != null) {
cur = cur.link;
}
return cur.data;
}
public Integer removeFirst() {
if (this.link == null) {
return this.data;
}
int removed = this.data;
this.data = this.link.data;
Link next = this.link.link;
this.link = next;
return removed;
}
public void remove(Integer data) {
if (this.link == null) {
removeFirst();
} else {
Link cur = this;
Link prev = null;
while (cur.link != null && cur.data != data) {
prev = cur;
cur = cur.link;
}
if(cur.link == null) {
prev.link = null;
cur = null;
}
if (cur != null) {
cur.data = cur.link.data;
cur.link = cur.link.link;
}
}
}
public Integer removeLast() {
Link prev = null;
Link cur = this;
while (cur.link != null) {
prev = cur;
cur = cur.link;
}
prev.link = null;
int removed = cur.data;
cur = null;
return removed;
}
public int size() {
Link cur = this;
int size = 0;
while (cur != null) {
cur = cur.link;
size += 1;
}
return size;
}
public void printList() {
Link prev = this;
while (prev.link != null) {
System.out.print(prev.data + " ");
prev = prev.link;
}
System.out.print(prev.data + "\n");
}
@Override
public String toString() {
Link prev = this;
StringBuffer sb = new StringBuffer();
while (prev.link != null) {
sb.append(prev.data);
prev = prev.link;
}
sb.append(prev.data);
return sb.toString();
}
}
Happy Coding
No comments:
Post a Comment