java複習之鏈表
主要複習單鏈表,多鏈表,雙向鏈表及相關操作
單鏈表
這裏出了點小問題,用框架多了,腦子瓦特了,break和return 混了,return強制結束當前的方法,不論在多少層嵌套中,break結束當前的循環(while也是個循環啊,qaq,基礎代碼不寫手生了啊!)
package learn;
public class LinkedList {
public static void main(String[] args) {
Node node1= new Node("1");
Node node2= new Node("2");
Node node3= new Node("3");
Node node4= new Node("4");
LinkList linkList = new LinkList();
linkList.add(node1);
linkList.add(node2);
linkList.add(node3);
linkList.add(node4);
linkList.list();
}
}
class Node{
public String data;
public Node next;
public Node(String data) {
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"data='" + data + '\'' +
'}';
}
}
class LinkList{
private Node head;
private Node temp;
public LinkList() {
head=new Node("0");
temp=head;
}
public void add(Node node){
while (true) {
if(temp.next==null){
break;
}
temp=temp.next;
}
temp.next=node;
}
public void list(){
if(head.next==null){
return;
}
temp=head.next;
while (true){
if(temp==null){
break;
}
System.out.println(temp);
temp=temp.next;
}
}
}
接下來是對插入的節點進行判斷,按順序輸出
這裏主要是對臨時標記(指針?引用)temp的使用,temp從頭節點開始,使用temp.next和新插入的節點進行比較,只要大於新插入的節點,那就進行插入,插入的過程就不說了,看代碼就兩行。
package learn;
public class LinkedList {
public static void main(String[] args) {
Node node1= new Node(1);
Node node2= new Node(2);
Node node3= new Node(3);
Node node4= new Node(7);
LinkList linkList = new LinkList();
linkList.addByOrder(node1);
linkList.addByOrder(node4);
linkList.addByOrder(node3);
linkList.addByOrder(node2);
linkList.addByOrder(new Node(5));
linkList.list();
}
}
class Node{
public int data;
public Node next;
public Node(int data) {
this.data = data;
}
@Override
public String toString() {
return "Node{" +
"data='" + data + '\'' +
'}';
}
}
class LinkList{
private Node head;
private Node temp;
public LinkList() {
head=new Node(0);
temp=head;
}
public void addByOrder(Node node){
temp=head;
boolean flag=false;
while (true){
if(temp.next==null){
break;
}
if(temp.next.data>node.data){
break;
}else if(temp.next.data==node.data){
flag=true;
break;
}
temp=temp.next;
}
if(flag==false){
node.next=temp.next;
temp.next=node;
}
}
public void add(Node node){
while (true) {
if(temp.next==null){
break;
}
temp=temp.next;
}
temp.next=node;
}
public void list(){
if(head.next==null){
return;
}
temp=head.next;
while (true){
if(temp==null){
break;
}
System.out.println(temp);
temp=temp.next;
}
}
}
再加一個刪除的方法,還是利用temp
public void delete(Node node){
temp=head;
while(temp.next!=null){
if(temp.next.data==node.data){
temp.next=temp.next.next;
break;
}
}
}