Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package hwl;
- /* @author abozainih */
- public class Hwl {
- public static void main(String[] args) {
- LinkedList<Integer> x = new LinkedList<>();
- x.addFirst(2);
- x.addFirst(10);
- x.addFirst(3);
- x.addFirst(18);
- x.addFirst(5);
- x.print();
- System.out.println("==============");
- x.sort();
- x.print();
- }
- }
- class Node<E> {
- E element;
- Node<E> next;
- public Node(E element){
- this.element= element;
- }
- }
- class LinkedList< E extends Comparable> {
- Node<E> head = null;
- Node<E> tail = null;
- int size = 0;
- public void addFirst(E x){
- if(size == 0){
- head=new Node<E>(x);
- tail = head;
- size++;
- }else {
- Node<E> temp = new Node<E>(x);
- temp.next = head;
- head = temp;
- size++;
- }
- }
- public void addLast(E x){
- if(size == 0){
- head=new Node<E>(x);
- tail = head;
- size++;
- }else {
- Node<E> temp = new Node<E>(x);
- tail.next = temp;
- tail = temp;
- size++;
- }
- }
- public void print(){
- Node<E> current = head;
- while(current != null){
- System.out.println(current.element);
- current= current.next;
- }
- }
- public void add(int index, E x){
- if(index == 0) addFirst(x);
- else if(index == size-1) addLast(x);
- else {
- Node<E> current = head;
- for (int i = 0; i < index; i++) {
- current = current.next;
- }
- Node<E> temp = current.next;
- current.next = new Node<E>(x);
- current.next.next= temp;
- size++;
- }
- }
- public void sort(){
- Node<E> current = head ;
- Node<E> current2 = current.next;
- E min = head.element;
- E temp;
- int pos = 0;
- for (int i = 0; i < size-1; i++) {
- for (int j = 0; j < size; j++) {
- if(current2 != null){
- if(min.compareTo(current2.element) > 0){
- pos = j ;
- min = current2.element;
- }
- current2= current2.next;
- }
- }
- temp = current.element;
- current.element = min;
- current = current.next;
- min = current.element;
- current2 = head;
- for (int j = 0; j <= pos; j++) {
- if(current2 !=null){
- if(j==pos){current2.element = temp;}
- current2= current2.next;
- }
- }
- current2 = current.next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement