insertList
(1) 鏈結串列的新增資料功能,請修改 insertList()方法,資料值不允許重複。
public void insertList(int data) {
Node new_node, p, q;
new_node = new Node(data);
p = q = first;
while (p != null && p.data < data) {
q = p;
p = p.next;
}
new_node.next = p;
if (p == first)
first = new_node;
else
q.next = new_node;
}
deleteList
(2) 鏈結串列的刪除資料功能,請修改 deleteList()方法,如果資料data順利被刪除,則傳回true;如果data未出現在串列之中,則傳回false表示刪除失敗。
public void deleteList(int data) {
Node p, q;
p = q = first;
while (p != null && p.data != data) {
q = p;
p = p.next;
}
if (p != null) {
if (p == first)
first = p.next;
else
q.next = p.next;
}
}
public void insertList(int data) {
Node new_node, p, q;
new_node = new Node(data);
p = q = first;
while (p != null && p.data < data) {
q = p;
p = p.next;
}
new_node.next = p;
if (p == first) {
first = new_node;
} else {
if (q.data != new_node.data) {
q.next = new_node;
}
}
}
public boolean deleteList(int data) {
boolean bret = true;
Node p, q;
p = q = first;
while (p != null && p.data != data) {
q = p;
p = p.next;
}
if (p != null) {
bret = true;
if (p == first) {
first = p.next;
} else {
q.next = p.next;
}
} else {
bret = false;
}
return bret;
}
很感動 謝謝...
class Node {
int data;
Node next;
public Node(int n) {
data = n;
next = null;
}
}
class List {
Node first;
public List() {
first = null;
}
// insertList
// (1) 鏈結串列的新增資料功能,請修改 insertList()方法,資料值不允許重複。
public void insertList(int data) {
Node new_node, p, q;
new_node = new Node(data);
p = q = first;
while (p != null && p.data < data) {
q = p;
p = p.next;
}
new_node.next = p;
if (p == first) {
first = new_node;
} else {
if (q.data != new_node.data) {
q.next = new_node;
}
}
}
// deleteList
// (2) 鏈結串列的刪除資料功能,請修改 deleteList()方法,如果資料data順利被刪
// 除,則傳回true;如果data未出現在串列之中,則傳回false表示刪除失敗。
public boolean deleteList(int data) {
boolean bret = true;
Node p, q;
p = q = first;
while (p != null && p.data != data) {
q = p;
p = p.next;
}
if (p != null) {
bret = true;
System.out.println("true 刪除成功");
if (p == first) {
first = p.next;
} else {
q.next = p.next;
}
} else {
bret = false;
System.out.println("false 刪除失敗");
}
return bret;
}
public void visitList() {
Node p = first;
while (p != null) {
System.out.println(p.data);
p = p.next;
}
System.out.println();
}
}
public class ListProc {
public static void main(String args[]) {
List list = new List();
int data;
for (int i = 1; i < 10; i++) {
data = i * 10 % 23;
list.insertList(data);
}
list.visitList();
for (int i = 1; i < 5; i++) {
list.deleteList(i * 20 % 13);
list.visitList();
}
}
}
但是這樣是正確的嗎?![![https://ithelp.ithome.com.tw/upload/images/20211218/20135157vXtwi0RFok.png]