Created
September 24, 2015 04:34
-
-
Save ayberk/1d8e7b2567c671a35ce6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.util.Random; | |
/** | |
* Created by ayberk on 9/23/15. | |
*/ | |
public class MyLinkedList | |
{ | |
Node head; | |
public MyLinkedList() { | |
this.head = null; | |
} | |
public void add(int data) { | |
Node node = new Node(data); | |
Node curr = this.head; | |
if (curr == null) { | |
this.head = node; | |
return; | |
} | |
while(curr.next != null) { | |
curr = curr.next; | |
} | |
curr.next = node; | |
} | |
public void remove(int data) { | |
if (head == null) { | |
return; | |
} | |
Node curr = this.head; | |
Node prev = null; | |
while (curr != null && curr.data != data) { | |
prev = curr; | |
curr = curr.next; | |
} | |
if (curr == null) { | |
// can't find :( | |
System.out.println("cannot find"); | |
return; | |
} | |
prev.next = curr.next; | |
} | |
public void printList() { | |
if (head == null) { | |
System.out.println("Empty List!!!"); | |
return; | |
} | |
while (head != null) { | |
System.out.print(head.data + " "); | |
head = head.next; | |
} | |
System.out.println(); | |
} | |
public static MyLinkedList generateRandomList(int size) { | |
int max = 100; | |
MyLinkedList list = new MyLinkedList(); | |
Random r = new Random(); | |
for(int i=0; i<size; i++) { | |
list.add(r.nextInt(max)); | |
} | |
return list; | |
} | |
private class Node { | |
int data; | |
Node next; | |
public Node(int data) { | |
this.data = data; | |
next = null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment