Java程式設計題——簡單實現List操作
阿新 • • 發佈:2021-02-15
實現一些List的基本操作:
package List;
public class Node {
public int val;
public Node next;
public Node(int val) {
this.val = val;
}
@Override
public String toString() {
return " " + this.val;
}
}
package List;
public class Main {
public static Node creatList(){
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
Node e = new Node(5);
a.next = c;
c.next = e;
e.next = d;
d.next = b;
return a;
}
public static void main(String[] args) {
Node head = creatList();
// 1.
System.out.println("列印連結串列的每個元素:");
for (Node cur = head; cur != null; cur = cur.next){
System.out.print(cur + " ");
}
}
}
測試2:
public static void main(String[ ] args) {
Node head = creatList();
System.out.println("找到連結串列的最後一個結點:");
Node cur = head;
while (cur != null && cur.next != null){
cur = cur.next;
}
System.out.println(cur.val);
}
測試3:
public static void main(String[] args) {
Node head = creatList();
System.out.println("找到連結串列的倒數第二個結點:");
Node cur = head;
while (cur != null && cur.next != null && cur.next.next != null){
cur = cur.next;
}
System.out.println(cur.val);
}
測試4:
public static void main(String[] args) {
Node head = creatList();
System.out.println("找到連結串列的倒數第二個結點:");
Node cur = head;
while (cur != null && cur.next != null && cur.next.next != null){
cur = cur.next;
}
System.out.println(cur.val);
}
測試5:
public static void main(String[] args) {
Node head = creatList();
System.out.println("計算連結串列中元素的個數:");
int count = 0;
for (Node cur = head; cur != null; cur = cur.next){
count++;
}
System.out.println(count);
}
測試6:
public static void main(String[] args) {
Node head = creatList();
System.out.println("找到連結串列中是否包含某個元素:");
int findVal = 5;
int index = 1;
Node cur = head;
for (; cur != null; cur = cur.next){
if (cur.val == findVal){
break;
}
index++;
}
if (cur == null){
System.out.println("未找到為 " + findVal + " 的值");
}else {
System.out.println("已找到為 " + findVal + " 的值");
System.out.println("該值在連結串列的第 " + index + " 位");
}
}
當 findVal 為 0 時: