如何解决Java中两个双向链表的串联
您好,尝试将两个双向链接列表连接在一起。我拥有的代码确实可以工作,但不能确定它是否正确。 concat方法是加入双向链表。例如,如果具有linkedString t =新的linkedString(“ Super”)和另一个linkedString s =新的linkedString =新的linkedString(“ man”),并且将通过执行linkedString newString = t.concat(s)来调用; concat的值应该是超人。但是我不确定我是否做得正确。问题是如何充分利用双向链表表示。
/*
* To change this license header,choose License Headers in Project Properties.
* To change this template file,choose Tools | Templates
* and open the template in the editor.
*/
package project2;
import static project2.Project2.*;
/**
*
* @author denge
*/
public class LinkedString <T> implements LinkedStringInterface <T> {
private class Node <T> {
protected T data; // the value of the data itself
protected Node <T> next;// // next current in the list
protected Node <T> prevIoUs; // link to prevIoUs current
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node <T> next) {
this.next = next;
}
public Node getPrevIoUs() {
return prevIoUs;
}
public void setPrevIoUs(Node <T> prevIoUs) {
this.prevIoUs = prevIoUs;
}
public Node(T value) {
this.data = value;
this.next = null;
this.prevIoUs = null;
}
public Node(T value,Node <T> newNext,Node <T> newPrevIoUs) {
this.data = value;
this.next = newNext;
this.prevIoUs = newPrevIoUs;
}
@Override
public String toString() {
return data.toString();
}
}
private Node <T> last; // tail of list
private Node <T> first; //head of list
private int counter; // keep track number of elements in the linked list.
/**
* constructors to initialize linklist counter to zero
*/
public LinkedString() {
counter = 0;
}
public LinkedString(char[] value)
{
for (int index = 0; index<value.length;index++)
{this.addToEnd(value[index]);
}
}
public LinkedString(String original){
for (int index = 0; index <original.length();index++)
{this.addToEnd(original.charat(index));
}
}
public char charat(int index)throws LinkedStringException{
if (index <0 || index>length())
{thowExeption(index);}
Node <T> current = this.find(index);
return (char) current.data;
}
public LinkedString<T> concat(LinkedString str) throws LinkedStringException
{
if(isEmpty())
{
throw new LinkedStringException("List is Empty");
}
LinkedString<T> tempString = new LinkedString(this.toString() + str.toString());
return tempString;
}
public LinkedString<T> substring(int beginIndex,int endindex) throws LinkedStringException{
if(isEmpty())
{
throw new LinkedStringException("Current List is empty.");
}
if (beginIndex<0)
{
thowExeption(beginIndex);
}
if (endindex>length())
{
thowExeption(endindex);
}
var current = this.find(beginIndex);
String tempString2="";
int tCounter=beginIndex;
while (current!=null&&tCounter<endindex+1)
{
tempString2 = tempString2 + current.data;
current=current.next;
tCounter++;
}
var str = new LinkedString(tempString2);
return str;
}
/**
* Puts value at the start of the list
*
* @param value Value to be added at the beginning of the list.
*/
private void addToFirst(char value) {
Node <T> current = new Node(value);
if (isEmpty()) {
first = last = current;
first.prevIoUs=null;
last.prevIoUs=null;
} else {
first.prevIoUs = current;
current.next = first;
first = current;
first.prevIoUs = null;
}
counter++;
}
/**
* Appends value to the end of the list
*
* @param value Value to be added at the end of the list.
*/
private void addToEnd(char value) {
Node node = new Node(value);
if (isEmpty()) {
first = last = node;
first.prevIoUs=null;
last.prevIoUs=null;
} else {
last.next = node;
node.prevIoUs = last;
last = node;
last.next=null;
}
counter++;
}
private void thowExeption(int index)
{
if (index<0)
{
throw new LinkedStringException("Beginning Index can not be less than 0. Beginning index provided " + index);
}
if (index>length())
{
throw new LinkedStringException("Ending Index can not be greater than " + length() +". Ending index provided " + index);
}
}
/**
* Searches the entire list to check to see if value is in the list.
*
* @param value The data is be compared with each item in the list.
* @return Returns true if value of the data exists in the list. Returns
* false if the value provided does not exists in the list.
*
*/
@Override
public boolean contains(T value) {
Node <T> current = first;
boolean isFound = true;
/*try {
indexOf(value);
} catch (LinkedStringException ex) {
isFound = false;
}*/
// while (current != null) {
// if (current.data == value) {
// isFound = true;
// return isFound;
// }
// current = current.next;
// }
return isFound;
}
private Node getPrevIoUs(Node <T> node) {
var current = first;
while (current != null) {
if (current.next == node) {
return current;
} // end if statement
current = current.next;
} // end of while loop
return null;
}
/**
* Method converts the list to an Array.
* @return Returns an char Array of values
*/
/**
* Prints out the items of the linked list.
*/
public void printList() {
println("\n-------------------Printing in the Forward direction------------------");
var current = first;
println("Number of Items that are in the list: " + length());
//println("first -> ");
while (current != null) {
System.out.print(current);
System.out.print(" ");
current = current.next;
}
println();
println("\n-------------------Printing in the reverse direction------------------");
current = last;
println("Number of Items that are in the list: " + length());
//println("first -> ");
while (current != null) {
System.out.print(current);
System.out.print(" ");
current = current.prevIoUs;
}
println();
}
public String toString(String direction){
String printedList="";
if (direction.equalsIgnoreCase("forward")){
var current=first;
while(current!=null)
{
printedList = printedList + current.toString() + " ";
current = current.next;
}}
if (direction.equalsIgnoreCase("reverse")){
var current=last;
while(current!=null)
{
printedList = printedList + current.toString() + " ";
current = current.prevIoUs;
}}
return printedList;
}
@Override
public String toString(){
String printedList="";
var current=first;
while(current!=null)
{
printedList = printedList + current.toString();
current = current.next;
}
return printedList;
}
/**
*
* @return Returns True if linked list is empty
*/
@Override
public boolean isEmpty() {
// returns true if empty and false if not empty
return counter == 0;
}
/**
* Returns number of items in the list. For example if the list contains 3 2
* 1 0 the return value is 4
*
* @return Size of the list.
*/
@Override
public int length() throws LinkedStringException {
if (isEmpty()){
throw new LinkedStringException("List is empty.");
}
return (counter);
}
/**
* Clears out entire content of the array.
*/
public void removeAll() {
if (isEmpty() == false) {
first = last = null;
counter = 0;
}
}//clears the entire link list.
/**
* @throws LinkedStringException Throws an exception if index provided is Out of
* Bounds or out of range.
* @param index Where in the list to retrieve the data.
* @return Returns the data store at a given index.
*
*/
@Override
public T get(int index) throws LinkedStringException {
if (index < 0 || index >= counter) {
thowExeption(index);
}
var current = find(index);
return (T) current.data;
}
/**
* Returns the first value of the linked list.
*
* @return
*/
private Node <T> find(int index) {
var current = first;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
/**
* Compares the Values of two list.
*
* @param List Second list to be compared.
* @return
* Returns true is both lists are the sames size all and values are equal to
* each other. If one sets of data are not equal then method will return false.
*/
public boolean equals (LinkedString List) throws LinkedStringException
{
if (this.isEmpty()&&List.isEmpty())
{
throw new LinkedStringException("Unable to Compare due to both Lists being empty.");
}
if(this.isEmpty())
{
throw new LinkedStringException("Unable to Compare due to an first list being empty.");
}
if (List.isEmpty())
{
throw new LinkedStringException("Unable to Compare due to an Second list being empty.");}
println("Comparing two link lists.");
var current = first;
var tempCurrent = List.first;
if (this.counter != List.counter)
{
return false;
}
while (current!=null){
println(current + " " + tempCurrent );
if (current.data != tempCurrent.data)
{
return false;}
current = current.next;
tempCurrent=tempCurrent.next;
}
return true;
}
}
/*
* To change this license header,choose License Headers in Project Properties.
* To change this template file,choose Tools | Templates
* and open the template in the editor.
*/
package project2;
//import java.util.LinkedList;
//import java.util.Scanner;
import java.util.*;
/**
*
* @author denge
*/
public class Project2 {
/**
* Prints out to the console with a newline character.
* @param x
*/
public static final void println(Object x) { System.out.println(x); }
/**
* Method prints a blank line.
*/
public static final void println() { System.out.println(); }
/**
* Printing out to the console.
* @param x data that needs to be printed out
*/
public static final void print(Object x) { System.out.print(x); }
public static void main(String[] args) {
Scanner input = new Scanner(system.in);
int index = 0;
char[] data = {'S','u','p','e','r'};
char[] data2 = {'B','o','y'};
LinkedString <Character[]> secondCList = new LinkedString<>(data2);
LinkedString <Character[]> firstCList = new LinkedString(data);
LinkedString <String> firstSList = new LinkedString("Wonder");
LinkedString <String> secondSList = new LinkedString("Woman");
LinkedString <String> tempList = firstSList.concat(secondCList);
// tempList = firstSList.concat(secondCList);
println("----Printing out table testing out length method--------");
println("LinkedList Names Contents Length");
println("------------------------------------------------");
println("firstCList\t\t\t\t" + firstCList.toString()+"\t\t\t\t"+firstCList.length());
println("secondCList\t\t\t\t" + secondCList.toString()+"\t\t\t\t\t"+secondCList.length());
println("firstSList\t\t\t\t" + firstSList.toString()+"\t\t\t\t"+firstSList.length());
println("secondSList\t\t\t\t" + secondSList.toString()+"\t\t\t\t"+secondSList.length());
println("tempList(concat)\t\t" + tempList.toString()+"\t\t\t"+tempList.length());
println("------testing out charat method----------");
println("\nThe 3 character of firstCList = "+ firstCList.charat(2));
println("The 2 character of firstSList = "+ firstSList.charat(1));
println("Testing out the get() at value 3 of secondSList: "+(Object) secondSList.get(2));
println("\n----testing out conatenation method -----------");
println("Concatenating firstCList with secondCList " + firstCList.concat(secondCList));
println("Concatenating firstSList with secondSlist " + firstSList.concat(secondSList));
println("Concatenating firstSList with secondCList " + firstSList.concat(secondCList));
println("Concatenating firstClist with secondSList " + firstCList.concat(secondSList));
println("\n---Testing out Substring Method----");
println("Printing the 2nd to 3rd character from firstCList: "+firstCList.substring(1,2));
println("Printing the 1st to 3rd character from firstSList: "+firstSList.substring(0,2));
println("Printing the 2 to 7 character from tempList: "+tempList.substring(1,6));
println("\nNow testing to see if the exception handling is working. clearing out firstCList");
println("Is firstCList empty: " + firstCList.isEmpty());
println();
firstCList.removeAll();
println("Cleared firstCList. Is firstCList empty: " + firstCList.isEmpty());
println();
try{
firstCList.length();
}
catch (LinkedStringException ex)
{
println("Exception handling is working. " + ex.getMessage());
}
firstCList = new LinkedString(data);
try{
println("Printing the 2 and 3 character from firstCList: "+firstCList.substring(1,10));
}
catch (LinkedStringException ex)
{
println("Exception handling is working. " + ex.getMessage());
}
try{
println("Printing the 2 and 3 character from firstCList: "+firstCList.substring(-1,10));
}
catch (LinkedStringException ex)
{
println("Exception handling is working. " + ex.getMessage());
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。