Javaはシングルチェーンコードを実現します.
3189 ワード
Javaは簡単なシングルチェーンコードを実現します.
package ;
import javax.print.attribute.standard.NumberOfDocuments;
import static com.sun.tools.classfile.CharacterRangeTable_attribute.Entry.length;
class Node{
Node next = null;
int data;
public Node(int data) {
this.data = data;
}
}
public class MyLinkedList {
Node head = null;
/**
*
* @param d
*/
public void addNode(int d){
//
Node newNode = new Node(d);
//
if(null == head){
head = newNode;
return;
}
//
Node tmp = head;
while (tmp.next!=null){
tmp=tmp.next;
}
tmp.next = newNode;
}
/**
*
* @param index
* @return 1 false
* true
*/
public boolean deleteNode(int index){
if(index<1||index>length()){
return false;
}
// , ,
if(index == 1){
head = head.next;
return true;
}
int i=1;
Node preNode = head;
Node curNode = head.next;
while (curNode!=null){
// , i ,
//i index ( index )
if(i==index){
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return true;
}
/**
*
* @return
*/
public int length(){
int length = 0;
Node tmp = head;
while (tmp.next!=null){
length++;
tmp = tmp.next;
}
return length;
}
/**
*
* @return true
*/
public boolean isEmpty(){
return null == head?true:false;
}
/**
*
* @return
*/
public Node orderList(){
int tmp=0;
Node curNode = head;
Node nextNode = null;
while (curNode.next!=null){
nextNode = curNode.next;
//
while(nextNode!=null){
if(curNode.data > nextNode.data){
tmp = curNode.data;
curNode.data = nextNode.data;
nextNode.data = tmp;
}
nextNode = nextNode.next;
}
curNode = curNode.next;
}
return head;
}
/**
*
*/
public void printList(){
Node tmp = head;
while(tmp!=null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public static void main(String[] args) {
MyLinkedList list = new MyLinkedList();
list.addNode(10);
list.addNode(3);
list.addNode(5);
list.addNode(1);
list.addNode(9);
System.out.println("length is "+list.length());
System.out.println("before order");
list.printList();
list.orderList();
System.out.println("after order");
list.printList();
}
}