Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- public class LinkedList {
- Node head;
- static class Node {
- int data;
- Node next;
- Node(int d)
- {
- data = d;
- next = null;
- }
- }
- public static LinkedList insert(LinkedList list, int data)
- {
- // Create a new node with given data
- Node new_node = new Node(data);
- new_node.next = null;
- // If the Linked List is empty,
- // then make the new node as head
- if (list.head == null) {
- list.head = new_node;
- }
- else {
- // Else traverse till the last node
- // and insert the new_node there
- Node last = list.head;
- while (last.next != null) {
- last = last.next;
- }
- // Insert the new_node at last node
- last.next = new_node;
- }
- // Return the list by head
- return list;
- }
- public static void printList(LinkedList list)
- {
- Node currNode = list.head;
- System.out.print("LinkedList: ");
- // Traverse through the LinkedList
- while (currNode != null) {
- // Print the data at current node
- System.out.print(currNode.data + " ");
- // Go to next node
- currNode = currNode.next;
- }
- }
- // Driver code
- public static void main(String[] args)
- {
- // Empty main, please insert
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement