Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class MyLinkedList {
- protected Element head;
- protected Element tail;
- void insertAt(int n){
- }
- public Element find(int mydata){
- Element starter = head;
- while(starter != null){
- if(starter.data == mydata){
- return starter;
- }
- starter = starter.next;
- }
- return null;
- }
- public String toString(){
- String result = "[ ";
- Element starter = head;
- while(starter != tail){
- result = result + String.valueOf(starter.data) + ", ";
- starter = starter.next;
- }
- result = result + String.valueOf(starter.data);
- result += " ]";
- return result;
- }
- public void append(int mydata) {
- Element element = new Element(mydata, null);
- if (head == null) head = element;
- else tail.next = element;
- tail = element;
- }
- public void prepend(int mydata) {
- Element element = new Element(mydata, head);
- if (head == null) tail = element;
- head = element;
- }
- public int countNodes() {
- int count = 0;
- Element e = head;
- while (e != null) {
- count++;
- e = e.next;
- }
- return count;
- }
- public int countNodes(int mydata) {
- int count = 0;
- Element e = head;
- while (e != null) {
- if (e.data == mydata)
- count++;
- e = e.next;
- }
- return count;
- }
- public void extractFirst() {
- if (head == null) throw new IllegalArgumentException("item not found");
- head = head.next;
- if (head == null) tail = null;
- }
- public void extractLast() {
- if (tail == null) throw new IllegalArgumentException("item not found");
- if (head == tail) head = tail = null;
- else {
- Element previous = head;
- while (previous.next != tail) previous = previous.next;
- previous.next = null;
- tail = previous;
- }
- }
- public void extract(int mydata) {
- Element element = head;
- Element previous = null;
- while (element != null && !(element.getData() == mydata)) {
- previous = element;
- element = element.next;
- }
- if (element == null) throw new IllegalArgumentException("item not found");
- if (element == head) head = element.next;
- else previous.next = element.next;
- if (element == tail) tail = previous;
- }
- public final class Element {
- int data;
- Element next;
- Element(int mydata, Element element) {
- data = mydata;
- next = element;
- }
- public int getData() {
- return data;
- }
- public Element getNext() {
- return next;
- }
- public void insertBefore(int mydata) {
- Element element = new Element(mydata, this);
- if (this == head) {
- head = element;
- return;
- }
- Element previous = head;
- while (previous.next != this) {
- previous = previous.next;
- }
- previous.next = element;
- }
- public void insertAfter(int mydata) {
- next = new Element(mydata, next);
- if (this == tail)
- tail = next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement