标签:
节点数据类的存储信息
1 class Node{ 2 Node next = null; 3 int data; 4 public Node(int data){this.data = data;} 5 }
对链表的具体操作(插入数据、删除数据、排序)
1 public class MylinkedList{ 2 Node head = null; 3 4 //向链表中插入数据 5 public void addNode(int d){ 6 Node newNode = new Node(d); 7 if(head == null){ 8 head = newNode; 9 return; 10 } 11 Node tmp = head; 12 while(tmp.next != null){ 13 tmp = tmp.next; 14 } 15 //add node to end 16 tmp.next = newNode; 17 } 18 19 20 //删除第index个节点 21 public Boolean deleteNode(int index){ 22 if(index<1 || index>length()){ 23 return false; 24 } 25 //删除链表第一个元素 26 if(index == 1){ 27 head = head.next; 28 return true; 29 } 30 int i = 1; 31 Node preNode = head; 32 Node curNode = preNode.next; 33 while(curNode != null){ 34 if(i == index){ 35 preNode.next = curNode.next; 36 return true; 37 } 38 preNode = curNode; 39 curNode = curNode.next; 40 i++; 41 } 42 return true; 43 } 44 45 //返回节点长度 46 public int length(){ 47 int length = 0; 48 Node tmp = head; 49 while (tmp != null) { 50 length++; 51 tmp = tmp.next; 52 } 53 return length; 54 } 55 56 57 //对链表进行排序 58 public Node orderList(){ 59 Node nextNode = null; 60 int temp = 0; 61 Node curNode = head; 62 while(curNode.next != null){ 63 nextNode = curNode.next; 64 while(nextNode != null){ 65 if(curNode.data > nextNode.data){ 66 temp = curNode.data; 67 curNode.data = nextNode.data; 68 nextNode.data = temp; 69 } 70 nextNode = nextNode.next; 71 } 72 curNode = curNode.next; 73 } 74 return head; 75 } 76 }
标签:
原文地址:http://www.cnblogs.com/Eason-S/p/5505764.html