So I am making a linked list and in my insertion, I need to maintain its order. So if I were to traverse through the linked list from the root to its trail with this insertion
-->
Insertion: 1 2 3
It should output -->
Output: 1 2 3
So far I have this code below. All this code does is output my insertion in reverse. So it prints ->
3
2
1
I want the program to maintain its insertion order by modifying my addLast() method. So when I print my Linked List it comes out the same way I inserted it.
public class LinkedListMeth
{
public static void main(String[] args)
{
FirstLinkedList list = new FirstLinkedList();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.traverseLast();
}
}
class FirstLinkedList
{
private class Node
{
private Node next;
private int data;
}
private Node last = null;
public void addLast(int d)
{
Node newNode = new Node();
newNode.data = d;
newNode.next = last;
last = newNode;
}
public void traverseLast()
{
Node head = last;
while (head != null)
{
System.out.println(head.data);
head = head.next;
}
}
If you want to stick with your exact current design, then one option to print the list in start-to-finish order would be to use recursion, something like this:
public void printFirstLinkedList(Node node) {
if (node == null) return;
printFirstLinkedList(node.next);
System.out.print(node.data + " ");
return;
}
printFirstLinkedList(yourList.last);
You should keep root of your linked list for traversing in insert order.
Here is an edited version of your code:
class FirstLinkedList {
private class Node {
private Node next;
private int data;
}
private Node root = null;
private Node last = null;
public void addLast(int d) {
Node node = new Node();
node.data = d;
if (root == null) {
root = node;
root.next = last;
last = root;
} else {
last.next = node;
last = last.next;
}
}
public void traverseLast() {
Node head = root;
while (head != null) {
System.out.println(head.data);
head = head.next;
}
}
}
Output is :
1
2
3
Related
I'm trying to implement a LinkedList, the problem I'm having is adding elements to this list, I've already added elements in the main class and want to know how to add elements at the beginning of the list and at the end of the list. The current is able to print, but when i add new elements they cant be seen. I also want to know about getting the size of the linked list.
class Node {
int data;
Node next;
Node(int data){
this.data = data;
}
}
public class LinkedList {
Node head;
int size;
public void AddBeginning(int data) {
Node newNode = new Node(data);
newNode.next = head;
this.size++;
head = newNode;
}
public void addAtEnd(int data) {
Node current = head;
while(current.next != null) {
current = current.next;
}
current.next = new Node(data);
}
public void getSize() {
System.out.println(size);
}
public void printList(Node head) {
Node current = head;
while (current !=null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}
}
public class Tester {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
Node head = new Node(25);
Node second = new Node(22);
Node third = new Node(7);
head.next = second;
second.next = third;
ll.AddBeginning(20);
ll.printList(head);
}
}
I would like to add 20 at the beginning and another integer at the end.
You are adding to Node 20 ll.AddBeginning(20); to LinkedList.head And Trying to print the list using Tester.head (declared in main method)
Solution:
Step 1 : Initialize LinkedList.head either
- Using constructor or
LinkedList ll = new LinkedList(head);
public LinkedList(Node head) {
this.head = head;
}
- Assign head to LinkedList object i.e., ll
ll.head = head; // Need to initialize Linked List with Head
Step 2 : No need to pass head variable to printList() function. It prints the LinkedList.head elements
ll.printList(); //Here you passing Tester.head not required
Code :
Tester main method
ll.head = head; // Need to initialize Linked List with Head
ll.AddBeginning(20); //Here actually adding node to linkedList head
ll.printList(); //Here you passing Tester.head not required
LinkedList.PrintList method
public void printList() {
Node current = this.head;//changed to linkedlist.head
while (current != null) {
System.out.print(current.data + "-->");
current = current.next;
}
System.out.print(current);
}
I am doing a linked list project for my class at school. Essentially we are supposed to make a linked list from scratch, and have add, delete, and find commands. No matter how hard I've been trying I cannot seem to get the list to display anything other than the head node. here are my classes starting from node
public class main {
public static void main(String args[]) {
for (int i = 0; i < 3; i++) {
LinkedList list = new LinkedList();
Node focus = new Node();
String start;
start = JOptionPane.showInputDialog("Enter 'A' to add an item"
+ "\n" + "Enter 'D' to delete an item\nEnter 'F' to find an item.");
if (start.equals("a") || start.equals("A")) {
focus.data = JOptionPane.showInputDialog("enter an item to ADD");
list.Add(focus);
while (focus != null) {
focus = list.head;
focus = focus.next;
JOptionPane.showMessageDialog(null, "your list is\n" + focus.getData());
}
}
}
}
}
public class Node {
String data;
Node next;
Node prev;
public Node(String data, Node next) {
this.data = data;
this.next = next;
}
Node() {
}
public void setData(String data) {
this.data = data;
}
public String getData() {
return this.data;
}
public void setNext(Node next) {//setnext
this.next = next;
}
public Node getNext() {
return next;
}
}
public class LinkedList extends Node {
Node head;
int listcount = 0;
public LinkedList() {
this.prev = null;
this.next = null;
this.listcount = 0;
}
LinkedList(Node Set) {
}
public void Add(Node n) {
Node current = this.prev;
if (current != null) {
current = this.prev;
this.prev = new Node();
} else {
head = this.prev = new Node();
current = head;
}
listcount++;
}
}
I think my biggest problem is the "your list is" part. I can't seem to get it to display anything other than the head node. I would really appreciate the help, as this has been giving me a huge headache. :)
First of all, why does your LinkedList extends the Node class? It's a linked list not a node. There's nothing coming before and after the linked list. So the linked list has no prev and next. All the elements are added in the list and the elements are inserted after the head node. The head of the node has a prev and a next. In the Add method, if the head of the list is null (i.e, the list is empty), the new element becomes the head of the list. Otherwise, the new node is inserted after the head.
public class LinkedList {
Node head;
int listcount = 0;
public LinkedList() {
this.head = null;
this.listcount = 0;
}
public void Add(Node n) {
Node current = this.head;
if (current == null) {
head = n;
} else {
Node prev = null;
while (current != null) {
prev = current;
current = current.next;
}
prev.next = n;
}
listcount++;
}
public String toString() {
StringBuilder builder = new StringBuilder();
Node current = this.head;
while (current != null) {
builder.append(current.data).append(", ");
current = current.next;
}
return builder.toString();
}
}
I added a toString method which loops over the list and builds a string with the content from each node.
In the main method there are a few problems. The linked list is initialised only once not every time you select a choice. If you initialise the linked list every time you select something, then the linked list will always be reinitialised and the only node that will contain will be the head node after you add the new element.
public class main {
public static void main(String args[]) {
String start;
boolean finished=false;
LinkedList list = new LinkedList();
while(!finished) {
start = JOptionPane.showInputDialog("Enter 'A' to add an item"
+ "\n" + "Enter 'D' to delete an item\nEnter 'F' to find an item.");
if (start.equals("a") || start.equals("A")) {
Node focus = new Node();
focus.data = JOptionPane.showInputDialog("enter an item to ADD");
list.Add(focus);
JOptionPane.showMessageDialog(null, "your list is\n" + list.toString());
}
else {
finished = true;
}
}
}
}
Try to go over the code and understand what is happening and why. Also use pencil and paper to understand the logic.
I am trying to write a simple class that reverse a singly linked list and return a constructed linked list. The code below is working if i make everything public which I dont want to. Anybody interested to address my question? (should I use doubly linked list? or it is possible with single link list?)
What I want is a function reverseList receives a ListNode Object return a ListNode Object (in reverse order). Like this:
originalNumber=OriginalNumber.reverseList();
//// my code
public class ReverseLinkList {
public static ListNode originalNumber=new ListNode();
public static ListNode reversedNumber=new ListNode();
public static void main(String[] args) {
//create 1->2->3->null
originalNumber.add(1);originalNumber.add(2);originalNumber.add(3);
System.out.print(num1.toString()+"\n");
//create 3->2->1->null
reversedNumber=originalNumber.reverseList;
}
}
class ListNode{
private class Node{
Object data;
Node next;
Node(int v){
data=v;
next=null;
}
public Object getData(){
return data;
}
public void setData(int v){
data=v;
}
public Node getNext(){
return next;
}
public void setNext(Node nextValue){
next=nextValue;
}
}
private Node head;
public void add(int data){
if(head==null){
head=new Node(data);
}
Node temp=new Node(data);
Node current=head;
if(current !=null){
while(current.getNext()!=null){
current=current.getNext();
}
current.setNext(temp);
}
}
public String toString(){
String output="";
if(head!=null){
Node current=head.getNext();
while(current!=null){
//System.out.println(output);
output+=current.getData().toString();
current=current.getNext();
}
}
return output;
}
public Node getHead(){
return head;
}
public static Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
}
The original and working code which I do not want
public class ReversedLinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node reverse(Node node) {
Node prev = null;
Node current = node;
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
void printList(Node node) {
while (node != null) {
System.out.print(node.data + "");
node = node.next;
}
}
public static void main(String[] args) {
ReversedLinkedList list = new ReversedLinkedList();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.printList(head);
head = list.reverse(head);
System.out.println("");
list.printList(head);
}
}
You're on the right track. You can make the member variables private & use the appropriate getters & setters:
public ListNode reverseList() {
Node prev = null;
Node current = this.getHead();
Node next = null;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return this;
}
This allows you print a reversed list:
System.out.println(originalNumber.reverseList());
Note that the originalNumber is itself manipulated. So, subsequent prints (System.out.println(originalNumber);) would still print the reversed list.
If you don't want the original to be modified, then there really isn't any other way apart from collecting all the data & then looping through in the reverse order & adding them into a new list:
public ListNode reverseList() {
int size = 0;
// Calculate size
Node current = this.getHead();
while (current != null) {
size++;
current = current.getNext();
}
int[] data = new int[size];
// Collect all data
current = this.getHead();
int index = 0;
while (current != null) {
data[index++] = current.getData();
current = current.getNext();
}
// Add to a new list in reverse order
ListNode reversed = new ListNode();
for (index = size - 1; index >= 0; index--)
reversed.add(data[index]);
return reversed;
}
That first scan to get the size can be skipped if size is tracked while adding elements to the list or by simply switching to an ArrayList instead of an array for data.
Finally there's the elegant recursive approach which also keeps the original ListNode intact:
public ListNode reverseRecursive() {
return recursive(this.getHead());
}
private ListNode recursive(Node node) {
if (node == null)
return new ListNode();
else {
ListNode listNode = this.recursive(node.next);
listNode.add(node.data);
return listNode;
}
}
To print:
System.out.println(originalNumber.reverseRecursive());
Here we needn't keep track of size & you make use of the call stack to naturally keep track & pop out the nodes in reverse.
the method 'insertAscending' only gives me the first number even after i enter new ones. can anyone help with what i'm doing wrong? Thanks.
public class LinkedList13 {
// Private inner class Node
private class Node{
int data;
Node link;
public Node(){
data = Integer.MIN_VALUE;
link = null;
}
public Node(int x, Node p){
data = x;
link = p;
}
}
// End of Node class
public Node head;
public LinkedList13(){
head = null;
}
public void insertAscending(int data){
Node node = new Node();
node.data = data;
if (head == null)
head = node;
Node p = head;
while (p.link != null)
{
if (p.link.data > data)
{ node.link = p.link;
p.link = node;
break;
}
p= p.link;
}
}
}
Hint: is (p.link != null) ever true?
First of all, you should return after setting the head of the list (when the first element is added).
Second of all, you should handle the case where the newly inserted node is the smallest in the list (and therefore should come first). Your loop never compares the added node to the head of the list.
Finally, if the added element wasn't inserted in the while loop, it should be inserted after the while loop.
public void insertAscending(int data)
{
Node node = new Node();
node.data = data;
if (head == null) {
head = node;
return;
} else if (node.data < head.data) {
node.link = head;
head = node;
return;
}
Node p = head;
boolean added=false;
while (p.link != null)
{
if (p.link.data > data)
{
node.link = p.link;
p.link = node;
added = true;
break;
}
p = p.link;
}
if (!added)
p.link = node;
}
Check out your if condition if(p.link.data > data) the only way a node gets into the list is when that is true. This means, that, if the value of data being inserted it greater than (or equal to) everything that's been inserted so far, it will be discarded.
An easy way to fix this is change break to return and add p.link=node at the end (after the loop).
In the following code, I am trying to understand one thing in the insertFirst() method that
Why is the last statement first =newLink; and not first.next=new Link;
Will it be wrong? Isn't there a "next" in first?
I know this code is right and I know that a node needs to be inserted at the beginning and all, but I need help understanding just one statement.
Is first =newLink; and first.next=new Link; not the same thing?
public class LinkedList {
private Link first;
public LinkedList()
{
first = null;
}
public boolean isEmtpy()
{
return(first==null);
}
public void insertFirst(int id, int dd)
{
Link newLink=new Link(id,dd);
newLink.next=first;
first =newLink;
}
}
No, it's right: the list inserts new links at the beginning. The old "first" becomes the new link's "next", and the new link is the new "first".
Why is the last statement first =newLink; and not first.next=new Link;
Because you're inserting a new first element and the "next" element is the old first element, which was set on the previous line.
Is first =newLink; and first.next=new Link; not the same thing?
No. first is the first and first.next is the second.
This is because you want to put new element to the beginning, so you must set new element to the head of list and this element should point on "old-head", and then you have:
new_elemnt->old_head->...
LinkedList::first is not a guard element. It really points to the first element of the list. If LinkedList::first == null, then the list is empty. If Link::next == null, then it's the last element (the null is called a guard element in this case).
Simple example of SingleLinkedList in Java
package com.ds;
public class SingleLinkedList {
private Node head;
public static void main(String[] args) {
SingleLinkedList linkedList = new SingleLinkedList();
linkedList.insert(5);
linkedList.insert(15);
linkedList.insert(45);
linkedList.insert(55);
linkedList.insert(58);
linkedList.insert(25);
// Print value of Single Linked list.
linkedList.print();
// delete node from tail side.
linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();
/*linkedList.delete();
linkedList.delete();
linkedList.delete();
linkedList.delete();*/
linkedList.print();
}
SingleLinkedList() {
head = null;
}
void insert(int val) {
Node temp = new Node();
temp.data = val;
temp.next = null;
if (head == null) {
head = temp;
} else {
Node k = head;
while (k.next != null) {
k = k.next;
}
k.next = temp;
}
}
// delete from tail.
void delete() {
// if it's first node
if (head == null || head.next == null) {
head = null;
} else {
Node n = head;
Node t = head;
while (n.next != null) {
t = n;
n = n.next;
}
t.next = null;
}
}
void print() {
Node k = head;
while (k != null) {
System.out.println(k.data);
k = k.next;
}
}
Node reverse() {
Node h = head;
Node p = null;
Node t = null;
while (h != null) {
t = h.next;
h.next = p;
p = h;
h = t;
}
return p;
}
class Node {
private int data;
private Node next;
}
}