我如何修改此代码,从将节点从第二个位置插入到第一个位置?
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
值设置为当前 head:
Node newHead = new Node(x);
newHead.next = head;
此时,新的头是newHead
,它已入到列表的开头。
您可以使用临时变量并执行以下操作:
newNode = newNode() //the node you want to insert
tmp = head //assuming that head is accessible
head = newNode
newNode.next = tmp
head = newNode