Why this function is not able to hold ref to linkedList element? - data-structures

My linkedList node is defined as following,
class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
and in my main function, I am trying to make a linkedlist from array like below,
public static void main(String[] args) {
int[] first={9,9,9,9};
ListNode firstNode=null;
ListNode firstNodeRef= firstNode;
for (int i =0;i<first.length;i++){
firstNode= new ListNode();
firstNode.val=first[i];
firstNode= firstNode.next;
}
}
Why firstNodeRef is null. Java being ref by value. and when comes to objects the value is actually the ref of object. so, shouldn't this work?

Because it's a reference to the value which stays null and not a reference to the variable.
I wrote some logic with comments to help explain the point
int[] first = {9, 9, 9, 9};
// keep head as a reference to your first node
ListNode head = new ListNode(first[0], null);
// curr (short for current) will initially be a reference to head's node (not the head variable)
ListNode curr = head;
for (int i = 1; i < first.length; i++) {
// create a new list node that will be referenced by curr.next
curr.next = new ListNode(first[i], null);
// update curr to reference our recently created node above
curr = curr.next;
}

Related

Question about Reverse Linked List (leetcode 206)

I know my code is completely wrong, but I do not know where I did wrong,
can anyone point out and explain what I did wrong?
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode current = head;
ListNode nextNode = head.next;
while (nextNode != null) {
prev = current;
current = nextNode;
current.next = prev;
nextNode = nextNode.next;
System.out.println(nextNode.val);
}
return current;
}
Changes:
head.next = null; // to make the end of the list as null
current.next = prev; // current is the reference to the node so changes to it will change node with reference nextNode also
public ListNode reverseList(ListNode head) {
if (head == null) {
return head;
}
ListNode prev = null;
ListNode current = head;
ListNode nextNode = head.next;
head.next = null; // to make the end of the list as null
while (nextNode != null) {
prev = current;
current = nextNode;
nextNode = nextNode.next; // first get next node, before ...
current.next = prev; // ... overwriting it here
// System.out.println(nextNode.val);
}
return current;
}
Alternative Solution
We can just say while head != null and then reverse it using a prev Node, finally we would return the prev. It'd be easier:
public final class Solution {
public static final ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode nextNode;
while (head != null) {
nextNode = head.next;
head.next = prev;
prev = head;
head = nextNode;
}
return prev;
}
}

Reversing singly linked list using recursion

I have written code to reverse singly linked list using recursion. It is working fine on lists of length less than or equal to 174725. But on lists of length greater than 174725 it gives a segmentation fault(Segmentation fault: 11) while reversing it via reverse() call. Can someone please explain this to me ?
#include <iostream>
using namespace std;
class Node
{
public:
int val;
Node *next;
};
class Sll
{
public:
Node *head;
private:
void reverse(Node *node);
public:
Sll();
void insert_front(int key);
void reverse();
void print();
};
void Sll::reverse(Node *node)
{
if (node == NULL) return;
Node *rest = node->next;
if (rest == NULL)
{
head = node;
return;
}
reverse(rest);
rest->next = node;
node->next = NULL;
return;
}
Sll::Sll()
{
head = NULL;
}
void Sll::insert_front(int key)
{
Node *newnode = new Node;
newnode->val = key;
newnode->next = head;
head = newnode;
return;
}
void Sll::print()
{
Node *temp = head;
while (temp)
{
temp = temp->next;
}
cout << endl;
return;
}
void Sll::reverse()
{
reverse(head);
return;
}
int main()
{
Sll newList = Sll();
int n;
cin >> n;
for (int i = 0; i < n; i++) newList.insert_front(i + 1);
newList.reverse();
// newList.print();
return 0;
}
List reversing function must be tail-recursive, otherwise it is going to overflow the stack when recursing over a long list, like you observe. Also, it needs to be compiled with optimisations enabled or with -foptimize-sibling-calls gcc option.
Tail-recursive version:
Node* reverse(Node* n, Node* prev = nullptr) {
if(!n)
return prev;
Node* next = n->next;
n->next = prev;
return reverse(next, n);
}
An iterative list reversion can be more easily inlined though and it does not require any optimization options:
inline Node* reverse(Node* n) {
Node* prev = nullptr;
while(n) {
Node* next = n->next;
n->next = prev;
prev = n;
n = next;
}
return prev;
}

reverse singly linked list java?

I have a problem ,I can't run this method , I want to reverse the nodes in a single Linkedlist.I say all Posts from Stackoverflow about reverse but they are different with my code.
There is my code
public node reverse(node head) {
node p,q;
if(head==null) {
return head;
}
p=head;
q=p.next;
if(q==null) {
return p;
}
q=reverse(q);
p.next.next=p;
p.next=null;
return q;
}public void printList(){
node currentNode = head;
while(currentNode != null){
System.out.print(currentNode.data);
currentNode=currentNode.next;
}
}
Main class
public class main {
public static void main(String[] args) {
linkedlist obj = new linkedlist();
obj.insertFirst(1);
obj.insertFirst(2);
obj.insertFirst(3);
obj.insertFirst(4);
obj.insertFirst(5);
obj.reverse(head);
obj.printList();
please give me a solution by there code.
Reversed the linked list:
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
/* Function to reverse the linked list */
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;
}
// prints content of double linked list
void printList(Node node) {
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given Linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
Your code makes little sense and hard to make it right. I would recommend to go for an easier and concise approach first like this.
public node reverse(node head) {
if(head == null || head->next == mull) {
return head;
}
node current = head;
node newHead = null;
node previous = null;
while(current != null) {
node nxt = current.next;
current.next = previous;
newHead = current;
previous = current;
current = nxt;
}
return newHead;
}

Return first unique number in a stream in constant time

How to write a static function that returns first unique number in a stream of numbers if current number is a terminating number (e.g. zero). Otherwise, it should return zero.
static int firstUnique(int number);
Time complexity should be O(1). What data structure should I use?
Use map and doubly linkedlist :
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
const int TERMINATOR = 0;
struct Node {
int data;
Node* next;
Node* prev;
};
int firstUnique(int number){
static unordered_map<int, Node*> numToIsUnique;
static Node* head = nullptr; // first unique
static Node* tail = nullptr; // last unique
if (number != TERMINATOR){
Node* newNode = new Node{number, nullptr, nullptr};
if (numToIsUnique.insert(make_pair(number, newNode)).second == false) {
// insert fails => number is not unique
// Need to delete from LinkedList
Node* nodeToDelete = numToIsUnique[number];
if (nodeToDelete != nullptr){ // delete only once
if (head == nodeToDelete && tail == nodeToDelete){
// head == tail - one node
head = nullptr;
tail = nullptr;
}
else if (head == nodeToDelete){
// head to delete
head = head->next;
head->prev = nullptr;
}
else if (tail == nodeToDelete){
// tail to delete
tail = tail->prev;
tail->next = nullptr;
}
else {
// delete node in the middle
nodeToDelete->prev->next = nodeToDelete->next;
nodeToDelete->next->prev = nodeToDelete->prev;
}
delete nodeToDelete;
numToIsUnique[number] = nullptr;
}
}
else {
// number is new => need to append at the end of link list (last unique)
if (head == nullptr){
// list is empty
head = newNode;
tail = head;
}
else if (head == tail){
// list has one node
tail = newNode;
newNode->prev = head;
head->next = tail;
}
else {
// list has more than one node
newNode->prev = tail;
tail->next = newNode;
tail = newNode;
}
}
return TERMINATOR;
}
else {
// Output head
if (head == nullptr){
return TERMINATOR;
}
else {
return head->data;
}
}
}

Traverse binary tree - no recursion, no stack, no tree modification

So for an application I am building I need to be able to traverse a binary tree without using recursion, stack or modifying the tree in any way after it's been created. My node struct is as follows:
typedef struct
{
ValueType value; //Data stored in node
int left_index; //Left child
int right_index; //Right child
int parent_index; //Parent node
}
I am storing my tree as a 1D array where the left child of each node is at index 2*i + 1, the right child is at 2*i + 2 and the parent is at [i-1]/2. If a node doesn't have a parent or child, it's associated index is -1.
The only iterative non-stack based algorithm I found was something called "Morris Traversal" as seen here: http://www.geeksforgeeks.org/inorder-tree-traversal-without-recursion-and-without-stack/
However Morris Traversal modifies the tree during the traversal which I cannot do.
I am willing to add whatever information is needed to each node just as long as I can write the algorithm given the above constraints.
Is what I'm asking for even possible? And if so, how would I go about doing it? Not really sure how to even begin.
Wouldn't a "while(!done)" loop be suffcient?
What you want is a threaded binary tree. The right pointer of all leaf nodes points to the node's in-order successor.
It's easy to create such a thing, and not difficult at all to update it when you insert or delete a node. If you have control of the node structure, then this is almost certainly what you want.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode parent;
public void traverse() {
TreeNode current = this.leftMost();
while (current != null) {
System.out.println("Current at " + current.val);
current = current.inOrderNext();
}
}
public TreeNode inOrderNext() {
if (right != null) {
return right.leftMost();
} else {
TreeNode current = this;
TreeNode above = this.parent;
while (true) {
if (above == null) {
return null;
} else {
if (above.left == current) {
return above;
} else {
current = above;
above = above.parent;
}
}
}
}
}
public TreeNode leftMost() {
TreeNode result = this;
while (result.left != null) {
result = result.left;
}
return result;
}
public static void main(String args[]) {
TreeNode first = new TreeNode();
first.val = 4;
TreeNode second = new TreeNode();
second.val = 2;
second.parent = first;
first.left = second;
TreeNode third = new TreeNode();
third.val = 1;
third.parent = second;
second.left = third;
third = new TreeNode();
third.val = 3;
third.parent = second;
second.right = third;
second = new TreeNode();
second.val = 6;
second.parent = first;
first.right = second;
third = new TreeNode();
third.val = 5;
third.parent = second;
second.left = third;
third = new TreeNode();
third.val = 7;
third.parent = second;
second.right = third;
first.traverse();
}
}

Resources