单链表创建总结 *创建 ListNode 结点类 有属性 val next 考虑现实使用val定义为一个no和若干val,toString()重写 *创建 SingleLinkedList 单链表类 有private属性 头指针head 需要初始化 *单链表类需要有的方法: *遍历方法:不为空、则从头指针.next首元结点开始遍历,直至尾部 *插入结点:分头插法、尾插法(temp指针向后移动直至尾部、temp.next = 入参) *修改结点:不为空、则从头指针.next首元结点开始遍历,直至no相等/找不到no,修改val *删除结点:从头指针.next首元结点开始遍历,直至no相等/找不到no,temp指向next.next
package LeetcodeExercise;
import java.awt.*;
public class SingleLinkedListTest {
public static void main(String[] args) {
ListNode n1 = new ListNode(1,"111");
ListNode n2 = new ListNode(2,"222");
ListNode n3 = new ListNode(3,"333");
SingleLinkedList singleLinkedList = new SingleLinkedList();
singleLinkedList.insertNodeTail(n1);
singleLinkedList.insertNodeTail(n2);
singleLinkedList.insertNodeTail(n3);
singleLinkedList.list();
singleLinkedList.updateNode(new ListNode(2,"789"));
singleLinkedList.deleteNode(1);
singleLinkedList.list();
}
}
class ListNode{
int no;
String value;
ListNode next;
public ListNode(int no, String value) {
this.no = no;
this.value = value;
this.next = null;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public ListNode getNext() {
return next;
}
public void setNext(ListNode next) {
this.next = next;
}
@Override
public String toString() {
return "ListNode{" +
"no=" + no +
", value=" + value +
'}';
}
}
class SingleLinkedList{
private ListNode head = new ListNode(0," ");//head不能动
//遍历
public void list(){
if(isEmpty()){
return;
}
ListNode temp = head.next;
while (true){
if(temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public boolean isEmpty(){
if(head.next == null){
System.out.println("空链表");
return true;
}
return false;
}
//根据no找到结点 ???考虑怎么复用 到底返回what
public ListNode listByNo(int no){
if(isEmpty()){
return null;
}
ListNode temp = head.next;
while (temp.no != no){
temp = temp.next;
}
System.out.println(temp);
return temp;
}
/**
* @description: 尾部插入节点
* @params [val] 值
* @return LeetcodeExercise.ListNode
*/
public void insertNodeTail(ListNode listNode){
ListNode temp = head;
while (true){
if(temp.next == null){
break;
}
temp = temp.next;
}
temp.next = listNode;
}
public void updateNode(ListNode listNode){
if(isEmpty()){
return;
}
ListNode temp = head.next;
boolean flag = false;
while (true){
if(temp == null) {
break;
}
if(temp.no == listNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.value = listNode.value;
}else {
System.out.println("no listnode.no like this!");
}
}
public void deleteNode(int no){
ListNode temp = head;
boolean flag = false;
while (true){
if(temp == null) {
break;
}
if(temp.no == no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.next = temp.next.next;
}else {
System.out.println("no listnode.no like this!");
}
}
}
标签:单链,ListNode,temp,no,value,next,相关,public
From: https://www.cnblogs.com/bbnltxdy/p/17674158.html