如何在链表头部之前添加新节点



我想问:如何在链表的头部之前添加一个新节点:下面是我的代码:

//   Definition for singly-linked list.
public class ListNode {
int val; 
ListNode next; 
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }

public void addAfter(ListNode thisnode, int x) {
ListNode newNode = new ListNode(x);
if(thisnode == null) {
//add before the head
newNode.next = this;

}//wrong here
else {
ListNode currentNext = thisnode.next;
thisnode.next = newNode;
newNode.next = currentNext;
}
return;
}//done addAfter this node


}

例如,输入列表2 100 300 800,l.addAfter(null,500);输出应为但是我的输出仍然是2 100 300 800。谢谢你。

在head前插入会改变head的值。这在方法内部是做不到的。

public ListNode addAfter(ListNode thisnode, int x) {
ListNode newNode = new ListNode(x);
if(thisnode == null) {
//add before the head
newNode.next = this;
return newNode;    
} else {
ListNode currentNext = thisnode.next;
thisnode.next = newNode;
newNode.next = currentNext;
}
return this;
}

调用者将其命名为l = l.addAfter(null,500);

首先,让你的代码清晰、易读和一致。以下是您的要求:

public class Node {
private int value;
private Node next;
public Node(int value) {
this.value = value;
next = null;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class ListNode {
private Node head;
public ListNode(Node head) {
this.head = head;
}
public Node getHead(){
return head;
}
// Here is your function
public void insertBeforeHead(int value) {
Node node = new Node(value);
node.setNext(head); 
head = node;
}
}

//节点类

public class SinglyListNode {
int val;
SinglyListNode next;
SinglyListNode(int x) { val = x; }
}

//单链表类

public class SinglyLinkedList {
private SinglyListNode head;
public SinglyLinkedList() {
head = null;
}
// add at beginning
public void addAtBeginning(int value){
SinglyListNode node = new SinglyListNode(value);
if (head != null) {
node.next = head;
}
head = node;
}
// print list
public void printList(){
System.out.println("printing linked list");
SinglyListNode curr = head;
while (curr != null){
System.out.println(curr.val);
curr = curr.next;
}
}
}

//主方法
public static void main(String[] args) {
SinglyLinkedList linkedList = new SinglyLinkedList();
linkedList.addAtBeginning(5);
linkedList.addAtBeginning(6);
linkedList.addAtBeginning(7);
linkedList.printList();
}

你总是可以让一个标题是不变的,并在它之后添加所有的新元素。例子:

Head - Link1 - Link2 - Link3

当你想添加newLink时,你可以用这种方式添加它。

Head - newLink - Link1 - Link2 - Link3

这样,你的头部信息永远不会丢失,它减少了丢失整个列表的机会。

你可以在这里探索实现它的代码库。

https://github.com/SayefReyadh/tutorials/tree/master/LinkedList-Bangla-Tutorial/LinkedListExample/src/linkedlistexample

方法实现为insertFrontLinkedList.java

最新更新