Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class LinkedList<DataType> {
- private Link<DataType> firstLink;
- private Link lastLink() {
- Link l = firstLink.getNext();
- if (l == null) {
- return firstLink;
- }
- while (l.getNext() != null) {
- l = l.getNext();
- }
- return l;
- }
- public int size() {
- int counter = 2;
- Link l = firstLink.getNext();
- if (l == null) {
- return 1;
- }
- while (l.getNext() != null) {
- l = l.getNext();
- counter++;
- }
- return counter;
- }
- public DataType get(int index) {
- if (index == 0) {
- return firstLink.getData();
- }
- int counter = 1;
- Link<DataType> l = firstLink.getNext();
- while (true) {
- if (counter == index) {
- return l.getData();
- }
- l = l.getNext();
- counter++;
- }
- }
- private Link getLink(int index) {
- if (index == 0) {
- return firstLink;
- }
- int counter = 1;
- Link<DataType> l = firstLink.getNext();
- while (true) {
- if (counter == index) {
- return l;
- }
- l = l.getNext();
- counter++;
- }
- }
- public void add(DataType data) {
- if (firstLink == null) {
- firstLink = new Link<>(data);
- } else {
- lastLink().link(new Link(data));
- }
- }
- public void pop() {
- if (size() == 1) {
- firstLink = null;
- } else if (size() != 0) {
- getLink(size() - 2).removeLink();
- }
- }
- public void pop(int index) {
- if (index == 0) {
- firstLink = null;
- } else {
- getLink(index - 1).link(getLink(index).getNext());
- }
- }
- public void insert(DataType data, int index) {
- Link l = new Link(data);
- l.link(getLink(index));
- if (index == 0) {
- firstLink = l;
- } else {
- getLink(index - 1).link(l);
- }
- }
- public void replace(DataType data, int index) {
- Link l = new Link(data);
- l.link(getLink(index).getNext());
- if (index == 0) {
- firstLink = l;
- } else {
- getLink(index - 1).link(l);
- }
- }
- private class Link<DataType> {
- private Link next;
- private DataType data;
- public Link(DataType data) {
- this.data = data;
- }
- public void link(Link link) {
- next = link;
- }
- public DataType getData() {
- return data;
- }
- public Link getNext() {
- return next;
- }
- public void removeLink() {
- next = null;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement