package com.harrison.class02;
public class Code03_DeleteGivenValue {
public static class Node{
public int value;
public Node next;
public Node(int v) {
this.value=v;
}
}
public static Node deleteGivenValue(Node head,int num) {
while(head!=null) {
if(head.value!=num) {
break;
}
head=head.next;
}
//头结点来到第一个不需要删除的位置
Node pre=head;
Node cur=head;
while(cur!=null) {
if(cur.value==num) {
pre.next=cur.next;
}else {
pre=cur;
}
cur=cur.next;
}
return head;
}
public static Node generateRandomLinkedList(int len, int value) {
int size = (int) (Math.random() * (len + 1));
if (size == 0) {
return null;
}
size--;
Node head = new Node((int) (Math.random() * (value + 1)));
Node pre = head;
while (size != 0) {
Node cur = new Node((int) (Math.random() * (value + 1)));
pre.next = cur;
pre = cur;
size--;
}
return head;
}
public static void printLinkedList(Node head) {
if(head==null) {
return;
}
while(head!=null) {
System.out.print(head.value+" ");
head=head.next;
}
}
public static void main(String[] args) {
int len=10;
int value=10;
Node node=generateRandomLinkedList(len,value);
System.out.println("原单链表:");
printLinkedList(node);
deleteGivenValue(node, 5);
System.out.println("\n删除给定值后的单链表:");
printLinkedList(node);
}
}
单链表删除给定值
猜你喜欢
转载自blog.csdn.net/weixin_44337241/article/details/121489202
今日推荐
周排行