//singly linked list and the create and delete of it classSingleLinkedList { //head node privateHeroNodehead=newHeroNode(0, "", "");
//create publicvoidadd(HeroNode heroNode) { HeroNodetemp= head; //find the last node of the linked list while (true) { if (temp.next == null) { break; }
temp = temp.next; } temp.next = heroNode; }
public HeroNode getHead() { return head; }
//another create //add the new node to the right place by order //if the no has existed, print error message publicvoidaddByOrder(HeroNode heroNode) { HeroNodetemp= head; booleanisExist=false; while (true) { if (temp.next == null) { break; } if (temp.next.no > heroNode.no) { break; } if (temp.next.no == heroNode.no) { isExist = true; break; } temp = temp.next; }
if (isExist) { System.out.println("This hero could not be added for the no of him(her) has existed."); System.out.println("The no is " + heroNode.no + "."); } else { heroNode.next = temp.next; temp.next = heroNode; } }
//print out publicvoidshowList() { if (head.next == null) { System.out.println("This linked list is empty."); return; }
HeroNodetemp= head.next; while (true) { if (temp == null) { break; }
System.out.println(temp); temp = temp.next; } }
//delete publicvoiddelNode(int no) { HeroNodetemp= head; booleanflag=false; //whether we found the node we need to delete while (true) { if (temp.next == null) { //whether we reach the end of the nodelist break; } if (temp.next.no == no) { flag = true; break; } temp = temp.next; } if (flag) { temp.next = temp.next.next; } else { System.out.println("The node doesn't exist."); } } }
其他方法
获取链表长度(get the length of the List)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/** * get the number of node in a linked list * * @param head head node * @return number of node */ publicstaticintgetNodeLength(HeroNode head) { if (head.next == null) { return0; } intlength=0; HeroNodetemp= head.next; while (temp != null) { length++; temp = temp.next; } return length; }
查找单链表中的倒数第k个结点(find the last k one node of a singly linked list)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//查找单链表中倒数第k个结点 //1. 编写一个方法,接收head结点与index值 //2. index表示单链表中的倒数第k个结点 //3. 先把链表从头到尾遍历一遍,得到总长度size //4. 从链表头开始遍历到第(size - index)个 publicstatic HeroNode findLastIndexNode(HeroNode head, int index) { if (head.next == null) { returnnull; } intsize= getNodeLength(head); if (index <= 0 || index > size) { returnnull; } HeroNodetemp= head.next; for (inti=0; i < size - index; i++) { temp = temp.next; } return temp; }