package com.fzw.sf; public class List4j { private Node head ; private int length; public List4j(){ head = new Node(null,null); length = 0; } public void addhead(Object item){ Node node = new Node(item,null); node.setNext(head.getNext()); head.setNext(node); length++; } public void addtail(Object item){ Node node = new Node(item,null); Node temp = head; while(null != temp.getNext()){ temp = temp.getNext(); } temp.setNext(node); length++; } public void addindex(Object item,int index){ Node node = new Node(item,null); Node temp = head; for(int i=0; i temp = temp.getNext(); } node.setNext(temp.getNext()); temp.setNext(node); length++; } public void find(int index){ if(index<1 || index >length){ System.out.print("此位置空!"); } Node temp = head; for(int i=0; i temp = temp.getNext(); } System.out.println("链表中第"+index+"个位置的值为"+temp.getData()); } public void delindex(int index){ if(index<1 || index >length){ System.out.print("位置不存在!"); } Node temp = head; for(int i=0; i temp = temp.getNext(); } temp.setNext(temp.getNext().getNext()); length--; } public void print(){ Node temp = head; while(null != temp.getNext()){ System.out.println(temp.getNext().getData()); temp = temp.getNext(); } System.out.println("链表长度为:"+length); } public static void main(String[] args){ List4j list = new List4j(); list.addhead(2); list.addhead(3); list.addhead(4); list.addtail(5); list.addindex("第二", 2); list.print(); list.find(3); } } |