gpt4 book ai didi

java - Java 列表的实现

转载 作者:行者123 更新时间:2023-11-29 10:17:07 25 4
gpt4 key购买 nike

<分区>

我要写一个社保号链表,自己实现所有操作。我编写了 Node 类和列表,但在实现 sortedGet(int index) 方法时遇到了问题。我在那个方法中做错了什么?

package listpackage;

import listpackage.SocialNode;

public class SortedListRefBasedDuplicates{
private SocialNode head;
private int numItems = 0;


public SortedListRefBasedDuplicates(){
head = null;
}

public SocialNode getHead(){
return this.head;
}

public boolean sortedIsEmpty(){
return numItems == 0;
}

public int sortedSize(){
return numItems;
}

public SocialNode sortedGet(int index){
if(index == 0)
return head;
//else if(index >= 0 && index < sortedSize()){
//for (int i = 0; i < index; i++){
//head = head.getNext();
//}
//return head;
//}else{
//return null;
//}
else
return null;
}

public void sortedAdd(int social){
if(this.sortedIsEmpty()){
head = new SocialNode(social);
head.setNext(null);
numItems++;
}else{
int socialIndex = locateIndex(social);
if(socialIndex == this.sortedSize()){
SocialNode curr = sortedGet(socialIndex-1);
SocialNode scn = new SocialNode(social);
curr.setNext(scn);
numItems++;
}else{
if(socialIndex == 0){
SocialNode scn = new SocialNode(social);
scn.setNext(head);
head = scn;
numItems++;
}else{
SocialNode curr = sortedGet(socialIndex-1);
SocialNode prev = sortedGet(socialIndex-2);
SocialNode scn = new SocialNode(social, curr);
prev.setNext(scn);
numItems++;
}
}
}
}

public void sortedDelete(int social){

}

public int locateIndex(int social){
if(numItems == 0)
return 0;
else{
int index = 0;
while(head != null){
if(head.getData() < social){
index ++;
head = head.getNext();
}
else{
break;
}
}
return index;
}
}
}

package listpackage;

public class SocialNode{
private int social;
private SocialNode next;

public SocialNode(int social){
this.social = social;
next=null;
}

public SocialNode(int social, SocialNode nextNode){
this.social = social;
this.next = nextNode;
}

public int getData(){
return social;
}

public SocialNode getNext(){
return next;
}

public void setSocial(int s){
social = s;
}

public void setNext(SocialNode s){
next = s;
}
}

添加了 sortedDelete 方法

public void sortedDelete(int social){
if(sortedIsEmpty()){
System.out.println("List is Empty");
}
else if(sortedSize() == 1){
if(head.getData() == social)
head = null;
}else{
SocialNode x = head;
if(x.getData() == social)
head = head.getNext();
else{
int count = 1;
while(x!= null){
if(x.getData() == social && x.getNext() != null){
sortedGet(count-1).setNext(sortedGet(count+1));
break;
}else{
sortedGet(count-1).setNext(null);
}
x = x.getNext();
count ++;
}
}
}
}

如何从给定节点值的列表中删除节点?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com