0% found this document useful (0 votes)
2 views2 pages

LinkedList Node Insertion Methods

The document describes how to insert a node at the beginning and end of a linked list. It defines a Node class with data and next fields and a LinkedList class with a head field. The insertAtBeginning method sets the next of the new node to the current head and makes the new node the new head. The insertAtEnd method adds a new node after the last node by traversing the list to find the last node and setting its next to the new node.

Uploaded by

raneem308
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

LinkedList Node Insertion Methods

The document describes how to insert a node at the beginning and end of a linked list. It defines a Node class with data and next fields and a LinkedList class with a head field. The insertAtBeginning method sets the next of the new node to the current head and makes the new node the new head. The insertAtEnd method adds a new node after the last node by traversing the list to find the last node and setting its next to the new node.

Uploaded by

raneem308
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Insert a node at the beginning of the list:

class Node {
int data;
Node next;
public Node(int data) {
[Link] = data;
[Link] = null;
}
}
class LinkedList {
Node head;
public void insertAtBeginning(int newData) {
Node newNode = new Node(newData);
[Link] = head;
head = newNode;
}
}

Insert a node at the end of the list:


class LinkedList {
Node head;
public void insertAtEnd(int newData) {
Node newNode = new Node(newData);
if (head == null) {
head = newNode;
return;
}
Node last = head;
while ([Link] != null) {
last = [Link];
}
[Link] = newNode;
}
}

You might also like