-1
我正在製作一個單向鏈表,我需要把刪除方法,但得到錯誤任何幫助嗎?單鏈表刪除值
public void remove(int index) {
getNode(index - 1).Next = getNode(index + 1);
}
我正在製作一個單向鏈表,我需要把刪除方法,但得到錯誤任何幫助嗎?單鏈表刪除值
public void remove(int index) {
getNode(index - 1).Next = getNode(index + 1);
}
這裏可能會出現很多可能的錯誤。首先,我會在做出任何更改之前進行更多驗證,就好像
像Apokai正確地指出,你需要在刪除時非常小心。
下面是刪除無論使用哪一個服務於目的的三種方法:
//Method to delete the first/head element
public void deleteAtFirst() {
if (head == null) {//If list is empty
System.out.println("Linked List EMPTY!!");
} else {//else if it is not empty
head = head.next;//assigning head the address of the next node
}
}
//Method to delete the last element
public void deleteAtLast() {
if (head == null) {//If list is empty
System.out.println("Linked List EMPTY!!");
} else if (head.next == null) {//else if it has only 2 elements
head = null;
} else {//else if it is not empty and has more than 2 elements
Node tmpNode = head;//taking a temporary node and initialising it with the first/head node
while (tmpNode.next.next != null) {//looping it till the 'second last' element is reached
tmpNode = tmpNode.next;
}
tmpNode.next = null;//assigning the next address of the second last node as null thus making it the last node
}
}
//Method to delete an element at a given position
//The first element is situated at 'Position:[0]'
public void deleteAtPosition(int pos) {
int size = getSize();//Getting the size of the linked list through a pre-defined method
if (head == null || pos > size - 1) {//if the position is beyond the scope of current list or the list is empty
System.out.println("Position: " + pos + "does not exist");
} else {
Node prevNode = null;
Node currNode = head;
if (pos == size - 1) {//if position is equal to size-1 then essentially the last element is to be deleted
deleteAtLast();
} else if (pos == 0) {//if position given is '0' then we need to delete the first element
deleteAtFirst();
} else {//else if it is any other valid position
for (int i = 0; i < pos; i++) {//looping till the desired position
prevNode = currNode;//the node just before the required position will be assigned here
currNode = currNode.next;//the current node
}
prevNode.next = currNode.next;//assigning the next address of previous node to the next of current node thus removing the current node from the list
}
}
}
接招如果你使用的最後一個,則上述兩種方法都存在在你的代碼照顧。此外,它採用另一種方法的getSize():
//Method to get the size of the list
public int getSize() {//return type is integer as we are returning 'int size'
if (head == null) {//if the list is empty
return 0;
}
int size = 1;//initialising size by one
Node tmpNode = head;//taking a temporary node and initialising it with the first/head node
while (tmpNode.next != null) {//looping till the end of the list
tmpNode = tmpNode.next;//incrementing node to the next node 'after every iteration' of the loop
size++;//incrementing the size
}
return size;//returning size
}
如果你告訴我們實際的錯誤是什麼它可能幫助。此外,這段代碼很可能不足以確定問題。 – jpw 2014-12-06 01:52:39