Putting text from txt file into linked list - java

I'm trying to tokenize lines of numeric expressions into a linked list for a CS Project. I have to use my own Linked List that I created in a previous lab.
I tokenize each number and operator of a line, and insert each token into a node in my linked list as they are tokenized. When I code the program to print out each token as it's tokenized, each token is printed. But when I tell it to print out the linked list that contains each token as a node, some operators are missing. I don't know what is the cause for this behavior.
Below is the method that creates the Linked List containing each token:
public static LinkedListTest ReadInFile(String path){
File file = new File(path);
LinkedListTest list = new LinkedListTest();
try {
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()){
list.insert(st.nextToken());
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
Below are the methods for inserting into a linked list and printing one:
public class LinkedListTest implements LinkedList {
private Node head;
public LinkedListTest(){
head = new Node();
}
public void insert(Object x){
if (lookup(x) == false){
if (head.data == null)
head.data = x;
else{
/*
Node NewNode = new Node();
NewNode.data = x;
NewNode.next = head;
head = NewNode;
*/
//InsertLast
Node temp = head;
while (temp.next != null){
temp = temp.next;
}
Node NewNode = new Node();
NewNode.data = x;
NewNode.next = null;
temp.next = NewNode;
}
}
}
public void printList(){
Node temp = head;
while (temp.next != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.print(temp.data + " ");
}
}

I solved it. The lookup clause on my insert function was screwing it up.

Related

Reversing linked list using stack?

This is a code that reverses linked list using stack. I got everything right from creating a linked list and getting input from the user, but I got some logic wrong. Iam trying to reverse linked list using stack, but it is only reversing two number if say suppose I give in three numbers. How do I get it right?
import java.util.*;
class LinkedList{
Node head;
static class Node{`
int data;
Node next;
Node(int d){
this.data = d;
next = null;
}
}
public static LinkedList insert(LinkedList list, int data){
Node new_node = new Node(data);
if(list.head == null){
list.head = new_node;
}
else{
Node last = list.head;
while(last.next != null){
last = last.next;
}
last.next = new_node;
}
return list;
}
public static LinkedList reverse(LinkedList list){
Stack<Integer> stack = new Stack<Integer>();
Node current = list.head;
while(current.next != null){
stack.push(current.data);
current = current.next;
}
while(!stack.isEmpty()){
System.out.println("The reversed list is: " + stack.pop());
}
return list;
}
}
public class Main
{
public static void main(String[] args) {
LinkedList l = new LinkedList();
Scanner sc = new Scanner(System.in);
int length = sc.nextInt();
for(int i=1; i<=length; i++){
int number = sc.nextInt();
l.insert(l,number);
}
l.reverse(l);
}
}
The problem lies with your reverse function. While reading the linked list your while loop logic is skipping the last item.
Correct function is:
public static LinkedList reverse(LinkedList list){
Stack<Integer> stack = new Stack<Integer>();
Node current = list.head;
while(current != null){ // instead of while(current.next != null)
System.out.println("Pushed Data:"+current.data);
stack.push(current.data);
current = current.next;
}
System.out.println("The reversed list is: ");
while(!stack.isEmpty()){
System.out.println(stack.pop());
}
return list;
}
Everything looks good except the line while(current.next != null){ as here you check for the next node instead of the current node. So you need to change this line to while(current != null){

Is the implementation for Graph using Adjacency list correct?

I am a beginner with DSA, Since the last couple of days, I was trying to find the correct implementation for the Graph using the adjacency list.
Below I provided the entire code for the way I thought the adjacency list should be implemented.
I have created a SinglyLinkedlist from scratch.
And I am using a Hashmap to improve the Time complexity.
The Integer key in the Hashmap acts as the VERTICE & consists of a LinkedList in its VALUE.
In the vertices, I am storing the Integer ID and in the LinkedList, I am storing all the Friend names for that particular ID.
The Graph has 3 methods:
InsertVertice(int ID ) - creates an empty LinkedList at given ID in hashmap.
insertDataAtID (int ID, String data) - inserts the Data into the LinkedList at the given ID.
printAllDataAtID(int ID) - prints all the friend names or Data present in a LinkedList at a given ID/key in the Hashmap.
Can you please go through the Implementation and advice of any mistakes?
Or better some suggestions on how an Adjacency list can be implemented more effectively?
Thank you for this effort.
import java.util.HashMap;
public class demo {
static HashMap<Integer,SinglyLinkedlist> graph = new HashMap<>();
public static void main(String[] args){
Graph graph = new Graph();
graph.insertVertice(101);
graph.insertDataAtID(101,"Deepesh");
graph.insertDataAtID(101,"Kiran");
graph.insertDataAtID(101,"Aryan");
graph.insertVertice(201);
graph.insertDataAtID(201,"Carl");
graph.insertDataAtID(201,"Arun");
graph.insertDataAtID(201,"Kishan");
graph.insertDataAtID(201,"Betth");
graph.printAllDataAtID(101);
graph.printAllDataAtID(201);
}
}
import java.util.HashMap;
public class Graph{
HashMap<Integer,SinglyLinkedlist> maplist = new HashMap<>();
void insertVertice(Integer id ){
maplist.put(id,new SinglyLinkedlist());
}
void insertDataAtID(Integer id, String data){
if (maplist.get(id)==null){
System.out.println("No such Vertice exist with id : " + id);
System.out.println("Create the Vertice first by calling insertVertice() method.");
}
SinglyLinkedlist linkedlist = maplist.get(id);
linkedlist.insertNode(data);
}
void printAllDataAtID(Integer id) throws NullPointerException {
if (maplist.get(id) == null) {
System.out.println("No such Vertice exist with id : " + id);
System.out.println("Create the Vertice first by calling insertVertice() method.");
} else {
SinglyLinkedlist linkedlist = maplist.get(id);
linkedlist.printAll();
}
}
}
public class SinglyLinkedlist {
Node head;
Node tail;
public static class Node {
Node next;
String data;
}
void insertNode(String data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) {
head = tail = newNode;
newNode.next = null;
} else {
Node temp = head;
while (temp.next != null) {
temp = temp.next;
}
temp.next = newNode;
newNode.next = null;
tail = newNode;
}
}
void removeLastNode() {
Node temp = head;
while (temp.next.next != null) {
temp = temp.next;
}
Node removedNode = temp.next;
tail = temp;
tail.next = null;
System.out.println("Removed value : " + removedNode.data);
}
void printAll() {
if (head == null) {
System.out.println("List is Empty !");
} else {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
}
}
boolean search(String data) {
if (head == null) {
System.out.println("List is Empty !");
} else {
Node temp = head;
while (temp != null) {
if (temp.data.equals(data)) {
System.out.println("Value found !");
return true;
}
temp = temp.next;
}
System.out.println("Value not found !");
}
return false;
}
}
You don't need to traverse the list to insert if you are maintaining tail node.
void insertNode(String data) {
Node newNode = new Node();
newNode.data = data;
if (head == null) {
head = tail = newNode;
newNode.next = null;
} else {
tail.next = newNode;
newNode.next = null;
tail = tail.next;
}
}

Is there any code which needs to be included for deleting the nodes in Java Linked List

Write a Java program to move the last element of the linked list in the front and rest of the element by one position, and then print the modified linked list.
NOTE: Remember you cannot use the LinkedList java class and its methods, you have to make your own LinkedList class and methods.
I have written the code to move the last node to the first but ii'm not able to delete the node whichever I wanted.
import java.util.*;
public class LinkedList {
Node head;
class Node
{
int data ;
Node next;
Node(int a )
{
data = a ;
next = null;
}
}
void movefront()
{
if(head == null || head.next == null)
return;
Node secLast = null;
Node last = head;
while(last.next!= null)
{
secLast = last;
last = last.next;
}
secLast.next=null;
last.next = head;
head = last;
}
void deleteNode(int key)
{
// Store head node
Node temp = head, prev = null;
// If head node itself holds the key to be deleted
if (temp != null && temp.data == key)
{
head = temp.next; // Changed head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change temp.next
while (temp != null && temp.data != key)
{
prev = temp;
temp = temp.next;
}
// If key was not present in linked list
if (temp == null) return;
// Unlink the node from linked list
prev.next = temp.next;
}
public void push (int new_data)
{
Node new_node = new Node(new_data);
new_node.next= head;
head = new_node;
}
void printList()
{
Node temp = head;
while(temp!=null)
{
System.out.println(temp.data + " ");
temp = temp.next;
} System.out.println();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Number of integers to be enetered in the list:");
Scanner sc = new Scanner(System.in);
LinkedList llist = new LinkedList();
Integer n= sc.nextInt();
Integer arr[]=new Integer[n];
System.out.println("Insert the elements of your array");
for(int i=0; i<=arr.length; i++)
{
n= sc.nextInt();
llist.push(n);
}
System.out.println(" Linked list before moving last to front : " );
llist.printList();
llist.movefront();
llist.deleteNode(2);
System.out.println(" Linked list after moving from front to last : ");
llist.printList();
}
}
Try:
public class LinkedList {
static Scanner sc = new Scanner(System.in);
Node head;
class Node
{
int data ;
Node next;
Node(int a )
{
data = a ;
next = null;
}
}
void movefront()
{
if(head == null || head.next == null)
return;
Node secLast = null;
Node last = head;
while(last.next!= null)
{
secLast = last;
last = last.next;
}
secLast.next=null;
last.next = head;
head = last;
}
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next= null;
if(head == null) {
head = new_node;
return;
}
Node last_Node = head;
while(last_Node.next != null) {
last_Node = last_Node.next;
}
last_Node.next = new_node;
}
void printList()
{
Node temp = head;
while(temp != null)
{
System.out.println(temp.data + " ");
temp = temp.next;
} System.out.println();
}
private void delete() {
Node current_Node = head;
if(current_Node == null) {
System.out.println("no element in list to be deleted");
return;
}
head = current_Node.next;
}
public static void main(String[] args) {
System.out.println("Number of integers to be entered in the list:");
LinkedList llist = new LinkedList();
Integer n= sc.nextInt();
Integer arr[]=new Integer[n];
System.out.println("Insert the elements of your array: ");
for(int i=0; i<arr.length; i++)
{
n= sc.nextInt();
llist.push(n);
}
System.out.println("Linked list before moving last to front: " );
llist.printList();
llist.movefront();
System.out.println("Linked list after moving from front to last: ");
llist.printList();
System.out.println("Deleting first element from the list: ");
llist.delete();
llist.printList();
}
}
Output:
Explanation:
Updated for(int i=0; i<=arr.length; i++) to for(int i=0; i<arr.length; i++) in main method as index start from 0 so it should go till arr.length-1 hence i<arr.length.
Updated push method. New node is inserted at the end of the linkedlist but in your code it was acting as stack.
Added delete method to remove first node. If head is null in that case list is empty hence no element can be removed from the list. If it contains element then head will point to current_Node.next;

Inserting tokens into Double Linked List

I'm trying to store a mathematical expression by tokenizing it and putting it into a doubly linked list I created in a lab assignment. The insert method I implemented in the list worked completely fine when I tested before handing in the lab, but when I print the contents of the list after inserting the expression's tokens, some tokens are missing. I know the String Tokenizer is working, as I had it print all the tokens and they all showed up just fine.
Is there something about how String Tokenizer tokenizes strings that prevents me from inserting them as generic Objects in my linkes list? I feel like there's some behavior I'm not aware of here.
For reference, the class containing the method which tokenizes the string and inserts it into a list:
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.*;
import java.util.*;
public class Calculator {
DoubleLinkedListTest infixstorage;
public Calculator(){
infixstorage = new DoubleLinkedListTest();
}
public static DoubleLinkedListTest ReadInFile(String path){
File file = new File(path);
DoubleLinkedListTest list = new DoubleLinkedListTest();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()){
list.insert(st.nextToken());
}
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return list;
}
}
Here is the code for my DoubleLinkedList:
public class DoubleLinkedListTest implements DoubleLinkedList {
private DoubleNode head;
private DoubleNode tail;
public DoubleLinkedListTest(){
head = new DoubleNode();
tail = new DoubleNode();
head.next = tail;
tail.prev = head;
}
public void insert(Object x){
if (lookup(x) == false){
if (head.data == null){
head.data = x;
}
else if (head.data != null && tail.data == null){
tail.data = x;
}
else{
DoubleNode NewNode = new DoubleNode();
NewNode.data = x;
NewNode.next = null;
NewNode.prev = tail;
tail.next = NewNode;
tail = NewNode;
}
}
}
//Runtime of insert method will be n, where n is the number of nodes
public void delete(Object x){
if (this.lookup(x).equals(true)){
if(x.equals(head.data)){
head.next.prev = null;
head = head.next;
}
else{
DoubleNode temp = head;
while(temp.next != null){
if (temp.next.next == null && (temp.next).data.equals(x)){
temp.next.prev = null;
temp.next = null;
break;
}
if ((temp.next).data.equals(x)){
temp.next.next.prev = temp;
temp.next = (temp.next).next;
break;
}
else{
temp = temp.next;
}
}
}
}
}
public Object lookup(Object x){
Boolean search = false;
if (x.equals(head.data)){
search = true;
}
else{
DoubleNode temp = head;
while (temp.next != null){
if (x.equals(temp.data)){
search = true;
break;
}
if (temp.next.next == null && x.equals(temp.next.data)){
search = true;
break;
}
else{
temp = temp.next;
}
}
}
return search;
}
public boolean isEmpty(){
if(head.next == tail && tail.prev == head)
return true;
else
return false;
}
public void printList(){
DoubleNode temp = head;
System.out.println(temp.data + " ");
while (temp.next != null){
temp = temp.next;
System.out.println(temp.data + " ");
}
}
public void printListRev(){
System.out.print(tail.data + " ");
while (tail.prev != head){
tail = tail.prev;
printList();
}
}
}
I figured it out. The scanner is reading multiple lines of the file at once. I thought that there was one line, but it just appears that way in the txt file. It's actually three lines sitting next to each other.
EDIT: False alarm, after deleting the other lines, it is still incorrectly reading the remaining line
EDIT 2: Or at least the print of the list is not correct

Deleting a node from a list

My problem: My delete node method works fine for deleting any specified node from a user created list except for the first element. How do I get this method to be able to delete the front of a list?
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
}
This is the full program code.
import java.io.*;
public class LinkedList {
public int num;
public node front;
//set front to null
public void init() {
front = null;
}
//make a new node
public node makeNode(int num) {
node newNode = new node();
newNode.data = num;
newNode.next = null;
return newNode;
}
//find the end of a list
public node findTail(node front) {
node current = front;
while(current.next != null) {
current = current.next;
}
return current;
}
//find a specified node
public node findSpot(node front, int num) {
node current = front;
boolean searching = true, found = false;
while((searching)&&(!found)) {
if(current == null) {
searching = false;
}
else if(current.data == num) {
found = true;
}
else {
current = current.next;
}
}
return current;
}
//delete a specified node
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
}
//add nodes to the end of a list
public void add2Back(node front, int num) {
node tail;
if (front == null) {
front = makeNode(num);
}
else {
tail = findTail(front);
tail.next = makeNode(num);
}
}
//add nodes after a specified node
public void addAfter(int num, node spot) {
node newNode;
newNode = makeNode(num);
newNode.next = spot.next;
spot.next = newNode;
}
//print out a list
public void showList(node front) {
node current = front;
while(current != null){
System.out.println(current.data);
current = current.next;
}
}
public static void main(String [] args) throws IOException{
//make a new list and node
LinkedList newList = new LinkedList();
node newNode = new node();
//add data to the nodes in the list
for(int j = 1; j < 10; j++){
newList.add2Back(newNode, j);
}
//print out the list of nodes
System.out.println("Auto-generated node list");
newList.showList(newNode);
//ask the user how many nodes to make, make those nodes, and show them
System.out.println("Please enter how many nodes you would like made.");
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData = inputReader.readLine();
int listLength = Integer.parseInt(inputData);
LinkedList userList = new LinkedList();
node userNode = new node();
for(int j = 1; j < listLength; j++) {
userList.add2Back(userNode, j);
}
userList.showList(userNode);
//ask the user to add a new node to the list after a specified node
System.out.println("Please enter a number for a node and then choose a spot from the list to add after.");
BufferedReader inputReader2 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData2 = inputReader2.readLine();
BufferedReader inputReader3 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData3 = inputReader3.readLine();
int newNodeValue = Integer.parseInt(inputData2);
int nodeInList = Integer.parseInt(inputData3);
userList.addAfter(newNodeValue, userList.findSpot(userNode, nodeInList));
userList.showList(userNode);
//ask the user to delete a specified node
System.out.println("Please enter a node to delete.");
BufferedReader inputReader4 = new BufferedReader(new InputStreamReader(System.in)) ;
String inputData4 = inputReader4.readLine();
int nodeToDelete = Integer.parseInt(inputData4);
userList.deleteNode(userList.findSpot(userNode, nodeToDelete), userNode);
userList.showList(userNode);
}
}
The problem is that your deleteNode does not modify the front member variable of your list, because the front variable inside deleteNode is a method parameter, not the instance variable front.
Here is what you need to do:
Exposing front as a public member of the LinkedList is a violation of encapsulation. Make front a private variable.
Remove parameter front from all methods that take it; use the private member front instead.
Add a check in deleteNode to see if the spot to be deleted is the front. If it is, perform a special operation that assigns front a new value, and exit; otherwise, do the while loop that you already have.
public void deleteNode(node spot, node front) {
node current = spot, previous = front;
if(front == spot) {
front = null;
return;
}
while(previous.next != current) {
previous = previous.next;
}
previous.next = current.next;
current = null;
}
you are starting to check from the front.next. So front itself is being ignored each time.
Delete a node from linklist in PHP by just passing that value to
linklist delete method....
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
{
$this->firstNode = NULL;
$this->lastNode = NULL;
$this->count = 0;
}
//deleting a node from linklist $key is the value you want to delete
public function deleteNode($key)
{
$current = $this->firstNode;
$previous = $this->firstNode;
while($current->data != $key)
{
if($current->next == NULL)
return NULL;
else
{
$previous = $current;
$current = $current->next;
}
}
if($current == $this->firstNode)
{
if($this->count == 1)
{
$this->lastNode = $this->firstNode;
}
$this->firstNode = $this->firstNode->next;
}
else
{
if($this->lastNode == $current)
{
$this->lastNode = $previous;
}
$previous->next = $current->next;
}
$this->count--;
}
}
$obj = new LinkList();
$obj->deleteNode($value);
}
?>
linklist delete method....
<?php
class ListNode
{
public $data;
public $next;
function __construct($data)
{
$this->data = $data;
$this->next = NULL;
}
function readNode()
{
return $this->data;
}
}
class LinkList
{
private $firstNode;
private $lastNode;
private $count;
function __construct()
}

Categories