gpt4 book ai didi

Java链表在第一个位置插入节点

转载 作者:行者123 更新时间:2023-12-01 16:23:54 31 4
gpt4 key购买 nike

我如何修改此代码,将节点从第二个位置插入到第一个位置?

static void insertAtMid(int x)
{

if (head == null)
head = new Node(x);
else {

Node newNode = new Node(x);

Node ptr = head;
int len = 0;


while (ptr != null) {
len++;
ptr = ptr.next;
}


int count = (len >=1)? 1 : 0;
ptr = head;


while (count-- > 1)
ptr = ptr.next;


newNode.next = ptr.next;
ptr.next = newNode;
}
}

static void display()
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
}

public static void main (String[] args)
{

head = null;
head = new Node(23);
head.next = new Node(45);
head.next.next = new Node(12);
head.next.next.next = new Node(67);

System.out.println("Linked list before "+
"insertion: ");
display();

int x = 55;
insertAtMid(x);

System.out.println("\nLinked list after"+
" insertion: ");
display();
}

最佳答案

要在链表的开头插入新节点,您所要做的就是创建一个新节点,然后将其 next 值设置为当前头:

Node newHead = new Node(x);
newHead.next = head;

此时,新的头是newHead,它已经被插入到链表的开头了。

关于Java链表在第一个位置插入节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62197753/

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