如何实现单链表的增删操作
Java程序员面试笔试宝典P232勘误,程序有BUG!!!
1 /** 2 * Created by ahu_lichang on 2017/7/25. 3 */ 4 //结点类 5 class Node{ 6 Node next = null; 7 int data; 8 public Node(int data){ 9 this.data = data; 10 } 11 } 12 public class HuaWeiOJTest { 13 //链表头的引用 14 Node head = null; 15 //插入元素 16 public void addNode(int d){ 17 Node newNode = new Node(d); 18 if(head == null){ 19 head = newNode; 20 return; 21 } 22 Node tmp = head; 23 while (tmp.next!=null){ 24 tmp = tmp.next; 25 } 26 tmp.next = newNode; 27 } 28 //删除元素 29 public Boolean deleteNode(int index){ 30 if(index<1 || index>length()){ 31 return false; 32 } 33 if(index == 1){//删除第一个元素 34 head = head.next; 35 return true; 36 } 37 int i=2;//因为第一个元素已经判断过了!所以这里从第二个元素开始就好。如果这里从第一个开始的话,会有BUG!!!(源程序:int i=1;) 38 Node preNode = head; 39 Node curNode = preNode.next; 40 while (curNode!=null){ 41 if(i == index){ 42 preNode.next = curNode.next; 43 return true; 44 } 45 preNode = curNode; 46 curNode = curNode.next; 47 i++; 48 } 49 return true; 50 } 51 //结点的长度 52 public int length(){ 53 int length = 0; 54 Node tmp = head; 55 while (tmp!=null){ 56 length++; 57 tmp=tmp.next; 58 } 59 return length; 60 } 61 //对链表节点进行排序,从小到大.返回头结点 62 public Node orderList(){ 63 Node nextNode = null; 64 int temp = 0; 65 Node curNode = head; 66 while (curNode.next!=null){ 67 nextNode = curNode.next; 68 while (nextNode!=null){ 69 if(curNode.data>nextNode.data){ 70 temp = curNode.data; 71 curNode.data = nextNode.data; 72 nextNode.data = temp; 73 } 74 nextNode = nextNode.next; 75 } 76 curNode = curNode.next; 77 } 78 return head; 79 } 80 //打印链表 81 public void printList(){ 82 Node tmp = head; 83 while (tmp!=null){ 84 System.out.println(tmp.data); 85 tmp = tmp.next; 86 } 87 } 88 89 public static void main(String[] args){ 90 HuaWeiOJTest list = new HuaWeiOJTest(); 91 list.addNode(5); 92 list.addNode(3); 93 list.addNode(1); 94 list.addNode(3); 95 list.deleteNode(4);//删除第四个元素 96 System.out.println(list.length()); 97 list.printList(); 98 list.orderList(); 99 System.out.println("----------------"); 100 list.printList(); 101 } 102 103 }
一起学习,一起进步