作者:飞天兔g_653 | 来源:互联网 | 2023-06-06 16:01
importjava.util.Stack;创建一个节点;classNode{publicintval;publicNodeNext;publicNode(){}
import java.util.Stack;
class Node{public int val;public Node Next;public Node() {}public Node(int val) {this.val = val;}
}
public class Demo {public static void main(String[] args) {Demo sb =new Demo();Node a =new Node(1);Node b=new Node(2);Node c=new Node(3);Node d=new Node(4);Node e=new Node(5);a.Next=b;b.Next=c;c.Next=d;d.Next=e;System.out.println(sb.found(a, 8));Node res = sb.Dele(a,2);sb.display(res);}public boolean found(Node list,int k){if(list==null) {System.out.println("链表为空");return false;}while (list!=null){if(list.val==k){return true;}list=list.Next;}return false;}public Node Dele(Node list,int k){if(list==null) {System.out.println("链表为空");return null;}Node head = new Node();head = list;while (list.Next!=null){if(list.Next.val==k){list.Next=list.Next.Next;return head;}list=list.Next;}return head;}public void clear(Node list){list.Next=null;}public void display1(Node list){Stack<Integer> stack = new Stack<>();if(list==null) {System.out.println("单链表为空");return;}while (list!=null){stack.push(list.val);list=list.Next;}while (!stack.isEmpty()){System.out.print(stack.pop()+"->");}}public void display(Node list){if(list==null) System.out.println("单链表为空");while (list!=null){System.out.print(list.val+"->");list=list.Next;}}public int Size(Node List){if(List==null) return -1;int count=1;while (List.Next!=null){count++;List.Next=List.Next.Next;}return count;}public Node Addfirst(Node list,int val){Node head = new Node(val);if(list==null) return head;head.Next=list;return head;}public Node Addlast(Node list,int val){Node node = new Node(val);if(list==null) return node;Node cur = new Node();Node head = list;while (list.Next!=null&&list!=null){cur=list.Next;list=list.Next;}cur.Next=node;return head;}public Node Addlistnum(Node list,int num,int val){Node head =new Node();head=list;Node headnew = new Node(val);if(list==null) return headnew;if(num<0||num>Size(list)){System.out.println("输入位置不和法");return null;}for(int i=0;i<Size(list);i++){list=list.Next;if(i==num){headnew.Next=list.Next;list.Next=headnew;return head;}}return head;}
}