[英]Sorted Insert into Singly Linked List from scratch
我一直在嘗試從頭開始創建僅包含字符串,但在插入時對其進行排序的排序鏈表。 這是我目前的代碼:
import java.util.Arrays;
public class SortedLinkedList {
private StringNode head = null;
/**
* Default Constructor for a sorted linked list
*/
public SortedLinkedList() {}
/**
* Will add a new node with the specified data to the correctly sorted
* position in the list
*/
public void add(String data) {
if (head == null) {
head = new StringNode(data);
}
StringNode temp = new StringNode(data);
StringNode current = head;
if (current != null) {
while (current.getNext() != null) {
if (current.getData().toString().compareTo(current.getNext().getData().toString()) < 0) {
temp.setNext(current.getNext());
current.setNext(temp);
} else
current.setNext(temp);
}
}
}
/**
* Will remove the node that matches the specified data from the list.
* Returns true if node is found, otherwise will return false
*/
public boolean remove(String data) {
StringNode current = head;
if (head != null) {
while (current.getNext() != null) {
if (current.getData().toString().equals(data)) {
current.setNext(current.getNext().getNext());
return true;
}
current = current.getNext();
}
}
return false;
}
/**
* Will cycle through the list and display each item on a new line
*/
public void display() {
if (head != null) {
StringNode current = head.getNext();
System.out.print("[");
while (current.getNext() != null) {
System.out.print(current.getData().toString() + ", ");
current = current.getNext();
}
System.out.print("]");
}
}
// Inner Class
class StringNode {
String data;
StringNode next;
public StringNode(String nodeData) {
next = null;
data = nodeData;
}
/**
* Getter of Data
*/
public String getData() {
return data;
}
/**
* Getter of Next
*/
public StringNode getNext() {
return next;
}
/**
* Setter of Data
*/
public void setData(String newData) {
data = newData;
}
/**
* Setter of Next
*/
public void setNext(StringNode nextNode) {
next = nextNode;
}
}
}
我已經能夠添加而無需插入排序,但是,當我嘗試在插入編碼中編寫代碼后,它就壞了。 似乎它不再添加任何值。 我的驅動程序的當前輸出:
public class Driver {
public static void main(String[] args) {
SortedLinkedList name = new SortedLinkedList();
name.add("v");
name.add("a");
name.add("b");
name.display();
}
}
在我的顯示方法第70行是一個空指針異常,這是我的while循環的創建。 我完全迷失了,需要一些指導。 謝謝。
實際上你想檢查current == null,因為最后一個元素的.getNext()是null。
while (current != null)
重構一點:
// should print [] for empty SLL; no dangling comma
public void display() {
String out = "[";
StringNode current = head;
while(current != null) {
out = out + current.getData();
current = current.getNext();
if (current != null)
out = out + ", ";
}
out += "]";
System.out.print(out);
}
編輯:此外,您的添加/刪除方法需要重新設計...嘗試在紙上逐步研究算法,然后將條件/操作轉換為Java。
例:
/**
* Will add a new node with the specified data to the correctly sorted
* position in the list
*/
public void add(String data) {
StringNode temp = new StringNode(data);
if(head == null) {
head = temp;
return; // only adding one node
}
StringNode previous = head;
if (data.compareTo(previous.getData()) < 0) {
head = temp; // temp < head, so we add it to the beginning
head.setNext(previous);
return; // done
}
StringNode current = previous.getNext();
while (current != null) {
if (data.compareTo(current.getData()) < 0) {
temp.setNext(current);
previous.setNext(temp);
return; // done
} else {
previous = current;
current = previous.getNext();
}
}
// current == null, so we reached the end of the list;
previous.setNext(temp);
}
我稍微重構了你的代碼並刪除了你寫的代碼注釋。 相反,我添加了一些自己的評論。
請仔細閱讀這些注釋,並考慮為您編寫的任何代碼編寫單元測試。 它將幫助您捕獲任何錯誤,並讓您對發送的代碼充滿信心。
package com.so36046948;
public class SortedLinkedList {
private StringNode head = null;
public SortedLinkedList() {}
public void add(String data) {
// Do null checks on Data.
if (head == null) {
// If we have no head, set head and return immediately.
head = new StringNode(data, null);
return;
}
StringNode previous = head;
StringNode current = head;
StringNode temp = new StringNode(data);
// Continue iterating till we reach the end of the list.
while (null != current) {
if (current.getData().compareTo(data) < 0) {
if (current == head) {
// Special handling for the case when the element being inserted is greater than head.
head = temp;
temp.setNext(current);
return;
}
break;
}
previous = current;
current = current.getNext();
}
// Break out of the while loop and reset the next pointers. Previous points to immediate
// greater element and current points to immediate element that is less than *data* being
// inserted.
previous.setNext(temp);
temp.setNext(current);
}
public void display() {
// Consider overriding toString method instead of creating a display method,
if (null == head) {
System.out.println("List is empty.");
return;
}
StringBuilder sb = new StringBuilder();
StringNode current = head;
sb.append("[");
while (current != null) {
sb.append(current.getData()).append(",");
current = current.getNext();
}
sb.append("]");
System.out.println(sb);
}
// Inner Class
class StringNode {
private final String data;
private StringNode next;
public StringNode(String nodeData) {
next = null;
data = nodeData;
}
public StringNode(String nodeData, StringNode next) {
this.next = next;
data = nodeData;
}
/**
* Getter of Data
*/
public String getData() {
return data;
}
/**
* Getter of Next
*/
public StringNode getNext() {
return next;
}
/**
* Setter of Next
*/
public void setNext(StringNode nextNode) {
next = nextNode;
}
}
public static void main(String[] args) {
// Consider writing unit tests. I have created skeletons of a few rudimentry tests,
// you may add more.
test_insertInDscendingOrder();
test_insertInAscendingOrder();
test_insertTwoElements();
test_insertSingleElement();
//test_insertNullData();
}
private static void test_insertInDscendingOrder() {
SortedLinkedList name = new SortedLinkedList();
name.add("v");name.add("b");name.add("a");name.display();
}
private static void test_insertInAscendingOrder() {
SortedLinkedList name = new SortedLinkedList();
name.add("a");name.add("b");name.add("c");name.add("d");
name.display();
}
private static void test_insertTwoElements() {
SortedLinkedList name = new SortedLinkedList();
name.add("a");name.add("b");name.display();
}
private static void test_insertSingleElement() {
SortedLinkedList name = new SortedLinkedList();
name.add("a");name.display();
}
private static void test_insertNullData() {
// This would fail, Consider handling null data.
SortedLinkedList name = new SortedLinkedList();
name.add("a");
name.add(null);
name.display();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.