大二的数据结构,链表。我一直都很头疼。
leetcode刷到一道关于链表的题,脑中一片混沌。
所以来复习一下。
import java.util.*; import java.io.*; class Node { protected Node next; protected int val; public Node(int x) { val=x; } public void display() { System.out.print(val+" "); } } public class LinkList { public Node first; int size; int pos=0; public LinkList() { this.first=null; } public LinkList(int x) { this.first=new Node(x); this.size++; } public boolean add(int index,int x) { if(index>size) return false; Node p=new Node(x); if(this.first==null) { this.first=p; size++; return true; } Node previous=this.first; Node current=this.first; while(pos<index) { previous=current; current=current.next; pos++; } p.next=current; previous.next=p; pos=0; size++; return true; } public Boolean remove(int index) { if(index>=size) return false; Node previous=this.first; Node current=this.first; while(pos<index) { previous=current; current=current.next; pos++; } current=current.next; previous.next=current; pos=0; size--; return true; } public int getSize() { return this.size; } public int findElement(int x) { Node p=this.first; int r=0; while(p!=null) { if(p.val==x) return r; else p=p.next; r++; } return -1; } public void show() { Node p=first; while(p!=null) { p.display(); p=p.next; } } public static void main(String[] args) { Boolean flag; LinkList l1=new LinkList(); LinkList l2=new LinkList(2); flag=l2.add(1,3); flag=l2.add(2,4); flag=l2.add(3,5); flag=l2.add(4,6); System.out.println(l2.findElement(7)); System.out.println(l2.findElement(3)); l2.show(); } }