有一说一 ,C的单链表创建(头插,尾插)思路蛮简单的,现在用JAVA写感觉也还行?虽然没有指针,但是代码看起来更加简单了
package linklist; public class Node { Node next =null; int data; public Node(int data) { this.data=data; } }
package linklist; public class SingleLinkedList { Node head=null; //链表头添加 public void addHead(int data) { Node node = new Node(data); node.next =head; head =node; } //打印 public void printLink() { Node curNode = head; while(curNode !=null) { System.out.println(curNode.data+" "); curNode = curNode.next; } System.out.println(); } //长度 public int length() { int length =0; Node curr = head; while(curr!=null) { length++; curr=curr.next; } return length; } //在尾部插入 public void addLast(int data) { Node node = new Node(data); if(head==null) { head = node; } else { Node temp =head; while(temp.next!=null) { temp =temp.next; } temp.next=node; } } //按索引插入 public void insertByIndex(int index,int data) { Node node = new Node(data); if(index<0||index>length()) { System.out.println("插入位置不对"); return ; } int length=1; Node tmp = head; while(tmp.next!=null) { length++; tmp=tmp.next; if(index== length) { node.next=tmp.next; tmp.next=node; return; } } } //按索引删除 public void deleteByIndex(int index) { Node temp = head; if(index<0||index>length()) { System.out.println("位置不对"); return; }else if(index ==0) { head=head.next; } else { for(int i=1;i<index;i++) { temp=temp.next; } temp.next=temp.next.next; } } public static void main(String[] args) { // TODO Auto-generated method stub SingleLinkedList list = new SingleLinkedList(); list.addLast(1); list.addLast(3); list.addLast(4); list.printLink(); } }