一、单链表的插入操作
单链表的插入操作是将值为X的新结点插入到单链表的第i个结点的位置上,即插入到数据元素ai-1与ai之间,其具体步骤如下:
1)找到ai-1的引用(存储位置)p;
2)生成一个数据域为X的新结点s;
3)设置p.next=s;
4)设置s.next=a;
示意图如下:
二、单链表的删除操作
单链表的删除操作是将单链表的第i个结点删去,其具体步骤如下:
1)找到ai-1的引用p;
2)令p.next指向ai的直接后继结点(即把ai从链上摘下)ai+1
示意图如下:
三、代码示例
/** * 数据元素 */ public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String toString(){ return "name is "+name+", age is "+age; } } /** * 结点 */ public class Node { Person data; Node next; public Node(Person data) { this.data=data; } } /** * 链表 */ public class MyLinkedList { Node head = null; // 链表头的引用 /** * 向链表中插入数据,放在链表的最后 * @param p:插入数据的内容 */ public void addNode(Person p) { Node node = new Node(p); if (head == null) { head = node; return; } Node tmp = head; while (tmp.next != null) { tmp = tmp.next; } tmp.next = node; } /** * 删除第index个结点 */ public boolean deleteNode(int index){ //删除元素的位置不合理 if(index<1 || index>length()){ return false; } //删除链表第一个元素 if(index == 1){ head = head.next; return true; } int i=2; Node preNode=head; Node curNode=preNode.next; while(curNode!=null){ if(i==index){ preNode.next=curNode.next; return true; } preNode=curNode; curNode=curNode.next; i++; } return true; } /** * 返回链表的长度 */ public int length(){ int length = 0; Node tmp = head; while (tmp != null) { length++; tmp = tmp.next; } return length; } public void printList(){ Node temp = head; while(temp!=null){ System.out.println(temp.data.toString()); temp=temp.next; } } /** * 对链表进行排序 */ public Node orderNode(){ Node nextNode = null; Person person; Node curNode = head ; while(curNode.next!=null){ nextNode = curNode.next; while(nextNode != null){ // 按年龄从大到小 if(curNode.data.getAge()< nextNode.data.getAge()){ person = curNode.data; curNode.data = nextNode.data; nextNode.data = person; } nextNode=nextNode.next; } curNode=curNode.next; } return head; } public static void main(String[] args){ MyLinkedList list = new MyLinkedList(); for (int i = 1; i <= 10; i++) { Person person=new Person(); person.setAge(i); person.setName("Name-"+i); list.addNode(person); } System.out.println("before order ..."); list.printList(); System.out.println("\nafter order ..."); list.orderNode(); list.printList(); } }