Skip to content

Instantly share code, notes, and snippets.

@so77id
Created March 31, 2020 06:03
Show Gist options
  • Select an option

  • Save so77id/dd7983e8cb5c8bb7d97c4c88ff539323 to your computer and use it in GitHub Desktop.

Select an option

Save so77id/dd7983e8cb5c8bb7d97c4c88ff539323 to your computer and use it in GitHub Desktop.
Example of ordered linked list in java
class List {
private Node head;
public List() {
this.head = null;
}
public void insert(int value){
Node n_node = new Node(value);
if (this.head == null) {
this.head = n_node;
return;
}
if (this.head.getValue() > n_node.getValue()){
n_node.setNext(this.head);
this.head = n_node;
return;
}
Node tmp;
for(tmp = this.head; tmp.getNext() != null; tmp = tmp.getNext()){
if(tmp.getNext().getValue() > n_node.getValue()) {
n_node.setNext(tmp.getNext());
tmp.setNext(n_node);
return;
}
}
tmp.setNext(n_node);
}
public void pop() {
if (this.head != null) {
this.head = this.head.getNext();
}
}
public boolean empty(){
if (this.head == null) return true;
else return false;
}
public Node top(){
Node tmp = this.head;
return tmp;
}
}
import java.util.Scanner; // Import the Scanner class
public class Main {
public static void main(String[] args){
int n, buff;
Node tmp;
Scanner scanner = new Scanner(System.in); // Create a Scanner object
List myList = new List();
n = scanner.nextInt();
for(int i=0; i < n; i++){
buff = scanner.nextInt();
myList.insert(buff);
}
while(!myList.empty()){
tmp = myList.top();
myList.pop();
System.out.println(tmp.getValue());
}
}
}
class Node {
private int value;
private Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
public Node(int value) {
this.value = value;
this.next = null;
}
public int getValue() { return (this.value); }
public void setValue(int value) { this.value = value; }
public Node getNext() { return (this.next); }
public void setNext(Node next) { this.next = next; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment