I am trying this program but i am not able to achieve deletion. The execution is going into infinite loop. Also, i am not sure if i am forming linked list properly.
What am i missing in the following program:
public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;
private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}
public static void main(String[] args) {
int k = 3;
Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);
second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;
Node result = removalKthNode(list, k);
int j = 1;
while(result.next!=null){
System.out.println(j+": "+result.item);
}
}
private static Node removalKthNode(Node first, int k) {
Node temp = first;
for(int i=1; i < k; i++) {
temp = temp.next;
}
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return temp;
}
}
THANKS A TON for answer and comments.. the working program is listed below:
public class SpecificNodeRemoval {
private static class Node {
String item;
Node next;
Node prev;
private Node(String item, Node next, Node prev) {
this.item = item;
this.next = next;
this.prev = prev;
}
}
public static void main(String[] args) {
int k = 3;
Node fourth = new Node("Fourth", null, null);
Node third = new Node("Third", fourth, null);
Node second = new Node("Second", third, null);
Node first = new Node("First", second, null);
second.prev = first;
third.prev = second;
fourth.prev = third;
Node list = first;
Node result = removalKthNode(list, k);
int j = 1;
while(result != null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}
}
private static Node removalKthNode(Node first, int k) {
Node temp = first;
for(int i=1; i < k; i++) {
temp = temp.next;
}
temp.prev.next = temp.next;
temp.next.prev = temp.prev;
return first;
}
}
The output is:
1: First
2: Second
3: Fourth
This looks like the culprit.
while(result.next!=null){
System.out.println(j+": "+result.item);
}
you are not progressing forward in the linked list.
I'm not exactly sure what you intended, but you may want to write as follows to avoid infinite loop...
while(result !=null){
System.out.println(j+": "+result.item);
result = result.next;
j++;
}
But again if you want to print whole linked list, you should not initialise result with the value returned from removalKthNode function. You should start from first.
Hope this makes sense.
You have several issues in your code:
1) The removalKthNode method should return the 1st element in the list to make your code print meaningful results (or you'll have to navigate to the 1st element again to output the remaining list.
2) The while loop which prints your list is wrong in two places.
a) You do not increment j, so you always put the same position for the items.
b) You do not really iterate through that list, meaning you do not reassign your variable result.
Try something like this:
int j = 1;
while (result != null) {
System.out.println(j++ + ": " + result.item);
result = result.next;
}
The code
Node result = removalKthNode(list, k);
now result = Third
and you have while loop as while(result.next!=null) which is always be in the Third element so it's going for infinite loop. Change the result as below
while(result!=null){
System.out.println(j+": "+result.item);
result = result.next;
}
Try this : Might help you to accompalish the Task:
package com.amazon;
class Linkedlist{
Node head;
public Linkedlist() {
head = null;
}
public Node addNode(int data){
Node newNode = new Node(data);
if(head==null) head = newNode;
else{
Node current = head;
while(current.next!=null){
current = current.next;
}
current.next = newNode;
}
return newNode;
}
}
class Node
{
Node next;
int data;
Node(int d)
{
data = d;
next = null;
}
}
public class DeleteEveryKthNodes {
void modifyList(Node head,int k){
Node current = head;
Node previous = null;
Node newHead = null;
if(current==null)return;
int count;
while (current != null) {
for (count = 1; count < k && current != null; count++) {
previous = current;
current = current.next; // 1--2--3--4--5
}
if (current != null) {
Node temp = current;
previous.next = current.next;
// current = null;
temp = null;
current = current.next;
}
}
current = head;
while(current!=null){
System.out.print(" "+current.data);
current = current.next;
}
}
public static void main(String args[]) {
Linkedlist list = new Linkedlist();
list.head = new Node(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
new DeleteEveryKthNodes().modifyList(list.head, 2);
//list.head.next.next.next.next = new Node(1);
}
}
Simple Java Script for circular - n=5 and k=3, it will delete every 3 element in circular list.
public class TEST {
public static int killed_position(int[] newarr,int n,int a,int p) {
int iteration=0;
while(true) {
if(newarr[p-1] != 0) {
iteration++;
if(iteration>a-1) {
break;
}
}
p++;
if(p>n) {
p=1;
}
}
return p;
}
public static int next_position(int[] newarr,int n,int a,int p) {
int iteration=0;
while(iteration<1) {
if(newarr[p-1] != 0) {
iteration++;
}
else {
p++;
if(p>n) {
p=1;
}
}
}
System.out.println("NEXT START ->" + p);
return p;
}
public static void main(String[] args) {
int n=5;
int k=3;
int newarr[] = new int[n];
int a=1;
for(int i=0;i<n;i++) {
newarr[i]=i+1;
}
for(int i=1;i<n;i++) {
System.out.println("START -> " + a);
a=killed_position(newarr, n,k,a);
newarr[a-1]=0;
System.out.println("KILLED -> " + a);
a=next_position(newarr, n,k,a);
System.out.println("---------------------");
}
System.out.println("POSITION FINAL MAN -> " + a);
System.out.println("POSITION FINAL MAN NAME -> " + a);
for(int i=0;i<n;i++) {
System.out.print(newarr[i]);
}
}
}
Related
I am working on a project for my Data Structures class that asks me to write a class to implement a linked list of ints.
Use an inner class for the Node.
Include the methods below.
Write a tester to enable you to test all of the methods with whatever data you want in any order.
I have to create a method called "public LinkedListOfInts reverse()". This method is meant to "Return a copy of your Linked List but in reverse order." I have my code for this method down below. However, when I try to reverse a list it only prints the head. For Example, if I have a list like "[16, 1, 8, 7, 10, 10, 14, 17, 11, 4,] and I try to reverse it my output is [ 16, ]. Does someone know how correct my code so I can reverse a linked list?
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts {
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
}
public LinkedListOfInts(LinkedListOfInts other) {
Node tail = null;
for (Node n = other.head; n != null; n = n.nextNode) {
if (tail == null)
this.head = tail = new Node(n.value, null);
else {
tail.nextNode = new Node(n.value, null);
tail = tail.nextNode;
}
}
}
public LinkedListOfInts(int[] other) {
Node[] nodes = new Node[other.length];
for (int index = 0; index < other.length; index++) {
nodes[index] = new Node(other[index], null);
if (index > 0) {
nodes[index - 1].nextNode = nodes[index];
}
}
head = nodes[0];
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++)
this.addToFront(random.nextInt(high - low) + low);
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
if (head == null)
return null;
Node current = head;
Node previous = null;
Node nextNode = null;
while (current != null) {
nextNode = current.nextNode;
current.nextNode = previous;
previous = current;
current = nextNode;
}
return this;
}
public String toString() {
String result = " ";
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result += ptr.value + " ";
return result;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 11:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 12:
System.out.println("toString");
System.out.println(list.toString());
break;
}
}
}
}
Here is a working example for reversing your LinkedList. Keep in mind that you are not copying the content of the LinkedList. So if you reverse the list, the original list's head is now the tail and returns only one int.
import java.util.Random;
import java.util.Scanner;
public class LinkedListOfInts{
Node head;
Node tail;
private class Node {
int value;
Node nextNode;
public Node(int value, Node nextNode) {
this.value = value;
this.nextNode = nextNode;
}
#Override
public String toString() {
return "Node{" +
"value=" + value +
", nextNode=" + nextNode +
'}';
}
}
public LinkedListOfInts(LinkedListOfInts other) {
System.out.println(other.tail);
head = other.head;
tail = other.tail;
System.out.println(this);
}
public LinkedListOfInts(int N, int low, int high) {
Random random = new Random();
for (int i = 0; i < N; i++) {
this.addToFront(random.nextInt(high - low) + low);
}
Node node=head;
while(node.nextNode!=null){
node = node.nextNode;
}
tail = node;
}
public void addToFront(int x) {
head = new Node(x, head);
}
public LinkedListOfInts reverse() {
Node previous = null;
Node curr = head;
Node nex;
while (curr != null)
{
nex = curr.nextNode;
curr.nextNode = previous;
previous = curr;
curr = nex;
}
head = previous;
return this;
}
public String toString() {
StringBuilder result = new StringBuilder(" ");
for (Node ptr = head; ptr != null; ptr = ptr.nextNode)
result.append(ptr.value).append(" ");
return result.toString();
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
LinkedListOfInts list = new LinkedListOfInts(10, 1, 20);
LinkedListOfInts copy = new LinkedListOfInts(list);
boolean done = false;
while (!done) {
System.out.println("1. Reverse");
System.out.println("2. toString");
switch (input.nextInt()) {
case 1:
System.out.println("Reverse the List");
System.out.println(copy.reverse());
break;
case 2:
System.out.println("toString");
System.out.println(list);
break;
}
}
}
}
In this linked list I am trying to delete a node and return the list after deleting the particular node. Here I am not using the Value to delete, I am using the position to delete that particular node. Here in my code the delete function seems to have no effect over the output. What am I doing wrong here?
import java.util.*;
class LinkedList{
Node head;
static class Node{
int data;
Node next;
Node(int d){
this.data = d;
next = null;
}
}
public LinkedList insert(LinkedList l, int data){
Node new_node = new Node(data);
if(l.head == null){
l.head = new_node;
}
else{
Node last = l.head;
while(last.next != null){
last = last.next;
}
last.next = new_node;
}
return l;
}
public LinkedList delete(LinkedList l, int position){
Node current = l.head;
if(position == 0){
current = current.next;
}
int index = 1;
while(index < position - 1){
current = current.next;
index++;
}
current = current.next.next;
Node iterating = l.head;
while(iterating != null){
System.out.print(iterating.data + " ");
iterating = iterating.next;
}
return l;
}
}
public class Main
{
public static void main(String[] args) {
LinkedList l = new LinkedList();
Scanner sc = new Scanner(System.in);
int number = sc.nextInt();
int position = sc.nextInt();
for(int i=0; i<number; i++){
int num = sc.nextInt();
l.insert(l,num);
}
l.delete(l,position);
}
}
current=current.next doesn't have any effect on the original LinkedList because with that line of code, you just change where the reference (named as current) points to.
Think about this way,
Node a = new Node()
Node b = new Node()
Node c = new Node()
a.next =b
a = c
These lines of code doesn't result in c being connected to b.
Change code to this:
if (position == 0) return l.head.next;
else {
Node head = l.head;
int index = 1;
Node itr = l.head;
while(index < position) {
itr = itr.next;
index++;
}
if(itr.next != null) itr.next = itr.next.next;
return head;
}
public LinkedList delete(LinkedList l, int position) {
Node previous = null;
Node current = l.head;
int index = 0;
while (current != null && index < position){
previous = current;
current = current.next;
index++;
}
if (current != null) {
if (previous == null) {
l.head = current.next;
} else {
previous.next = current.next;
}
}
System.out.print("[");
Node iterating = l.head;
while (iterating != null) {
System.out.print(iterating.data + ", ");
iterating = iterating.next;
}
System.out.println("]");
return l;
}
The problem in java is that to delete a node either the head must be changed to its next, or the previous node's next must be changed to current's next.
Then too current might become null, have reached the list's end, position > list length.
I'm trying to write a program that will go forwards in a circular doubly linked list a certain amount of times and backwards in the same list a certain amount of times. If both methods end up at the same number then the number is 'worthy' and is removed from the list. If the methods don't end up at the same element on the list then they are unworthy and are removed from the list as well. I've written the method for going forwards and backwards a certain amount of times but I'm having difficulty with removing the elements once they have been deemed worthy or unworthy. This is what I have so far. Any help would be greatly appreciated.
import java.util.Arrays;
public class LinkedList {
private Node head;
private Node end;
LinkedList(){
head = end = null;
}
public void addAtStart(int x){
if (head == null) {
Node new_node = new Node(x);
new_node.data = x;
new_node.next = new_node.prev = new_node;
head = new_node;
} else if (head != null) {
Node last = (head).prev;
Node new_node = new Node(x);
new_node.data = x;
new_node.next = head;
(head).prev = new_node;
new_node.prev = last;
last.next = new_node;
}
}
public void printOutput(int N, int k, int m){
System.out.println("Output" + "\n" + "------" + "\n");
printCandidates(N,k,m);
}
public void printCandidates(int N, int k, int m){
int unworthy[] = new int[N];
int worthy[] = new int[N];
int count = 0;
int run = 0;
Node temp = head;
do {
if (forwards(k) == backwards(m)){ // puts in worthy list and deletes from linked list
worthy[count] = forwards(k);
count += 1;
System.out.println("hello");
deleteElement(forwards(k));
} else if (forwards(k) != backwards(m)){ //put in unworthy list and delete from linked list
unworthy[run] = forwards(k);
unworthy[run+1] = backwards(m);
run += 2;
System.out.println("goodbye");
deleteElement(forwards(k));
deleteElement(backwards(m));
}
} while (temp != null);
System.out.println("Removed candidates from being elected");
System.out.println(Arrays.toString(unworthy));
System.out.println("Worthy candidates");
System.out.println(Arrays.toString(worthy));
}
int forwards(int k){
int run = 0;
int x = 0;
Node temp = head;
while (temp.next != head){
if(run == (k)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
int backwards(int m){
int run = 0;
int x = 0;
Node temp = head;
Node last = head.prev;
temp = last;
while (temp.next != head){
if(run == (m)){
x = temp.data;
}
temp = temp.next;
run += 1;
}
return x;
}
public void deleteElement(int elementToBeDeleted){
Node temp = head;
while (temp.next != head){
if(temp.data == elementToBeDeleted){
temp.setNext(temp.next);
}
temp = temp.next;
}
}
This is my driver:
public class Program2 {
public static void main(String[] args) {
LinkedList ll = new LinkedList();
for (int i = 1; i < 11; i++){
ll.addAtStart(i);
}
int N = 10;
int k = 4;
int m = 3;
System.out.println("N = " + N + ", " + "k = " + k + ", " + "m = " + m + "\n");
ll.printOutput(N,k,m);
}
}
This is my node class:
public class Node {
public int data;
public Node next;
public Node prev;
// Constructor to intialize/fill data
public Node(int data){
this.data = data;
}
// set the address of next node
public void setNext(Node temp) {
this.next = temp;
}
// get the address of next node
public Node getNext(){
return this.next;
}
public Node getPrev(){
return this.prev;
}
public void setPrev(Node temp) {
this.prev = temp;
}
// to get data of current node
public int getData(){
return this.data;
}
}
EDIT: As part of this exercise I need to write the class myself, therefore why I am implementing my own LinkedList.
reverse second half linkedlist
example:
even number:
2->1->3->4->5->6->7->8 =====> 2->1->3->4->8->7->6->5 ;
odd number: 5->7->8->6->3->4->2 ======> 5->7->8->2->4->3->6, the
middle one also need be reversed
class ListNode
{
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class ReverseRightHalfLinkedList
{
public static void main(String[] args)
{
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
ListNode res = reverse(node1);//line 31
// ListNode node = node1;
// while (node != null)
// {
// System.out.println(node.val);
// node = node.next;
// }
}
public static ListNode reverse(ListNode start)
{
int counter = 0;
ListNode node = start;
ListNode pre = start;
while (node!= null)
{
counter += 1;
node = node.next;
}
for (int i=0; i<counter/2; i++)
{
pre = start;
start = start.next;
}
ListNode cur = start;
if (counter%2 ==0)
{
while (cur != null)
{
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
}
else
{
pre = pre.next;
cur = start.next;
System.out.println(pre.val);
System.out.println(cur.val);
while (cur != null)
{
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
System.out.println("-----");
System.out.println(pre.val); // line 90
System.out.println(cur.val);
System.out.println("-----");
System.out.println();
}
}
return start;
}
}
Firstly, I got an error message.
Exception in thread "main" java.lang.NullPointerException at
ReverseRightHalfLinkedList.reverse(OA2.java:90) at
ReverseRightHalfLinkedList.main(OA2.java:31)
Secondly, I tried to print the order of reversed linked list, it is still in order. It was not reversed.
Please help me to figure out these two problems. Thanks a lot!
Basing on #passion's idea. I got a more concise code.
class ListNode
{
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class ReverseRightHalfLinkedList
{
public static void main(String[] args)
{
ListNode node1 = new ListNode(2);
ListNode node2 = new ListNode(1);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
ListNode node5 = new ListNode(5);
ListNode node6 = new ListNode(6);
ListNode node7 = new ListNode(7);
ListNode node8 = new ListNode(8);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
node7.next = node8;
ListNode res = reverse(node1);
ListNode node = node1;
while (node != null)
{
System.out.println(node.val);
node = node.next;
}
}
public static ListNode reverse(ListNode start)
{
int counter = 0;
ListNode node = start;
ListNode pre = start;
ListNode result = start;
while (node!= null)// for count how many elements in linked list
{
counter += 1;
node = node.next;
}
for (int i=0; i< (counter / 2) ; i++)//no matter counter is even or odd, when it divided by 2, the result is even
{
pre = start;
start = start.next;
}
ListNode temp = null;
ListNode preNext = null;// this variable is used to track the next val behind pre
// for example, 2->1->3->4->5->6->7->8
// at this moment, pre:4, start:5
// I treated 5->6->7->8 as an independent linkedlist
// I reversed the linkedlist
// Finally, set the pre node's next value to the reversed linkedlist's head
// The first half and second half have been connected together
while (start != null)
{
temp = start.next;
start.next = preNext;
preNext = start;
start = temp;
}
pre.next = preNext;
return start;
}
}
You need reverse right half list , so you need to save last node of the left half and the header of the list , so than when right half get reversed , you can link them with the left half and return the whole list .
I have change your reverse method :
public static ListNode reverse(ListNode start)
{
int counter = 0;
ListNode node = start;
ListNode pre = start;
ListNode result = start;
while (node!= null)
{
counter += 1;
node = node.next;
}
int end = counter % 2 == 0 ? counter / 2 : (counter- 1) / 2 ;
for (int i=0; i< end ; i++)
{
pre = start;
start = start.next;
}
ListNode tlist = null,temp ;
while(start != null){
temp = start.next;
if(tlist == null){
tlist = start;
start.next = null;
}else{
start.next = tlist;
tlist = start;
}
start = temp;
}
pre.next = tlist;
return start;
}
Hope this code helps you understand.
class MainClass {
public static void main(String args[]) {
Node head = new Node("Sameer");
//Adding data to my linked list
Node temp = addNode("Monica", head);
temp = addNode("Doug", temp);
temp = addNode("Eric", temp);
temp = addNode("Charlie", temp);
temp = addNode("Dan", temp);
temp = addNode("Enrique", temp);
temp = addNode("Ankitha", temp);
addNode("Chad", temp);
SolveMidLinkedList(head);
}
//method to add a node to the linked list
static Node addNode(String str, Node node) {
Node newNode = new Node(str);
node.link = newNode;
return newNode;
}
//method to reverse the right hald of the linkedlist
static void SolveMidLinkedList(Node head) {
int LinkedListSize = 0;
Node temp = head;
Node LastEle = null, MiddleEle = null, temp1 = null, temp2 = null;
//While loop to find the size of the linkedlist and also to find the last element in the linkedlist
while (temp != null) {
LastEle = temp;
temp = temp.link;
LinkedListSize++;
}
//Printing the names
temp = head;
System.out.println("Before rearranging the linked list");
while (temp != null) {
System.out.println(temp.name);
temp = temp.link;
}
//The main procedure
temp = head;
int iCount = 1;
while (temp != null) {
//Not changing the order of first half of the linked list
if (iCount <= (LinkedListSize / 2)) {
MiddleEle = temp;
} else {
//Reversing the order of second half(right side half) of the linked list.
temp2 = temp.link;
temp.link = temp1;
temp1 = temp;
}
temp = temp.link;
iCount++;
}
//At the end asssigning the middle element to the last element of the linked list.
MiddleEle.link = LastEle;
//Printing the names
temp = head;
System.out.println("After rearranging the linked list");
while (temp != null) {
System.out.println(temp.name);
temp = temp.link;
}
}
}
//General definition of Node in a linked list.
class Node {
Node link = null;
String name;
Node(String str) {
this.name = str;
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication2;
class LinkedList {
static Node head;
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
Node rev(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;
}
Node reverse(Node node) {
int count =0;
Node doo = node;
Node mid_pre = node;
Node mid = node;
while(doo.next != null){
if((count & 1) == 1){
// mid_pre = mid;
mid = mid.next;
}
doo = doo.next;
count++;
}
// System.out.println(" midd ddddd :"+mid_pre.data+" "+mid.data);
mid.next = rev(mid.next);
return node;
}
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(1);
list.head.next = new Node(2);
list.head.next.next = new Node(3);
list.head.next.next.next = new Node(4);
list.head.next.next.next.next = new Node(5);
list.head.next.next.next.next.next = new Node(6);
//// 1 2 3 4 5 6
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);
}
}
Why not do something very straightforward. We know the size of the list. We can use list.get(counter) to iterate from the end to the centre. There was a bit of challenge when the list size was even or odd but its doable.
public static void reverseFromEndToCentre() {
List list = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5,6,7,8,9,10));
int midOfList = (int)Math.ceil(list.size() / 2);
int lenthOfList = list.size();
int counterFirstHalf =0;
while(counterFirstHalf<midOfList){
System.out.println(list.get(counterFirstHalf));
counterFirstHalf++;
}
int counterSecondHalf = lenthOfList;
while( counterSecondHalf > counterFirstHalf){
counterSecondHalf--;
System.out.println(list.get(counterSecondHalf ));
}
}
Here's a way to reverse second half(right) of linked list.
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
void append(struct Node** head_ref, int new_data)
{
struct Node* new_node=(struct Node*)malloc(sizeof(struct Node));
new_node->data=new_data;
new_node->next=NULL;
struct Node* last=*head_ref;
if(*head_ref==NULL){
*head_ref=new_node;
return;
}
while(last->next!=NULL)
last=last->next;
last->next=new_node;
return;
}
int display(struct Node* n)
{
int m=0;
printf("\n");
while(n!=NULL)
{
printf(" %d ",n->data);
n=n->next;
m=m+1;
}
return m;
}
void reverse(struct Node** head_ref, int mid)
{
if(*head_ref==NULL)
{
printf("\nEmpty List cannot be reversed");
return;
}
struct Node* last=*head_ref;
struct Node* second_last;
struct Node* beg=*head_ref;
int c=1;
while(c<=mid){
second_last=last;
last=last->next;
c=c+1;
}
struct Node* prev=NULL;
struct Node* current=last;
struct Node* next;
while(current != NULL)
{
next=current->next;
current->next=prev;
prev=current;
current=next;
}
*head_ref=beg;
second_last->next=prev;
}
int main()
{
int size;
struct Node* head=NULL;
int i,mid;
for(i=0;i<11;i++)
{
append(&head,rand()%19 +1);
}
size=display(head);
printf("\n Size of linked list: %d",size);
if(size%2==0)
mid=(size+1)/2;
else
mid=size/2;
reverse(&head, mid);
display(head);
return 0;
}
I have created my own custom Linked List (code is below). Now, I can't understand how to create an array of that Linked list like LinkedList[] l = new LinkedList[10]. Can anyone help me.
class Node {
public int data;
public Node pointer;
}
class LinkedList {
Node first;
int count = 0;
public void addToEnd(int data){
if(first == null){
Node node = new Node();
node.data = data;
node.pointer = null;
first = node;
count = 1;
return;
}
Node next = first;
while(next.pointer != null){
next = (Node)next.pointer;
}
Node newNode = new Node();
newNode.data = data;
newNode.pointer = null;
next.pointer = newNode;
count++;
}
public Node getFirst(){
return first;
}
public Node getLast(){
Node next = first;
while(next.pointer != null)
next = next.pointer;
return next;
}
public int[] get(){
if(count != 0){
int arr[] = new int [count] ;
Node next = first;
int i = 0;
arr[0]= next.data;
while(next.pointer != null){
next = next.pointer;
i++;
arr[i] = next.data;
}
i++;
return arr ;
}
return null ;
}
public int count(){
return count;
}
}
I'm going to guess that your problem is just that when you create an array of objects, like
LinkedList[] lists = new LinkedList[10];
you get an array full of nulls; you need to create objects to store in the array:
for (int i=0; i<lists.length; ++i)
lists[i] = new LinkedList();