How do I join two linked lists in C? - linked-list

I'm wanting to complete two linked lists in preparation for an exam
here is what I have so far
1 - reverse the elements in a linked list
2 - append list2 to the end of list one
I got help with the reverse function off someone in my course and have tried to comment out each step to understand what is going on but I am struggling. If you could also help me out with that it would be fantasticcaalll
In the combine function I am just confused overall
When do I use '&' and when do I use '*'?
typedef struct node *list;
typedef struct node {
int value;
list whateverNextIsCalled;
} node;
// Reverse list
list reverse (list inputList){
list outputList = NULL;
while (inputList != NULL) {
/*
nodePtr points to the first element in the inputList
*/
node *nodePtr = inputList;
/*
Make the head pointer of inputList point to the next element
*/
inputList = inputList->whateverNextIsCalled;
/*
???? help point 1
*/
nodePtr->whateverNextIsCalled = outputList;
/*
???? help point 2
*/
outputList = nodePtr;
}
return outputList;
}
// Add one list to the end of another
void combine (list list1, list list2){
/*
Point to the first value of list1
*/
node *current = list1;
/*
Find the last node of list1
*/
while(current->whateverNextIsCalled != NULL) {
current = current->whateverNextIsCalled;
}
//connect the last node of toList and the first node of fromList
current->whateverNextIsCalled = &list2;
list1 = current;
}

you can just reach to the last of the first linked list and in its next where there will be null just put the start of next linked list
i dint understand why you have reversed the list

Related

LinkedList pointer explanation

So I get a little idea of how a linked list work and how the head node points to another node that contains data and also the address of the next node. I've also looked at examples. I've been looking at this code I found for the past five hours confused on how under the display() method that current = head points to the next node. I keep thinking head.next = null and doesn't point at the next node. Can someone explain to me how head.next is pointing to the next node or when did it acquired the address because I can't find when in the code it does.
public class SinglyLinkedList {
//Represent a node of the singly linked list
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
//Represent the head and tail of the singly linked list
public Node head = null;
public Node tail = null;
//addNode() will add a new node to the list
public void addNode(int data) {
//Create a new node
Node newNode = new Node(data);
//Checks if the list is empty
if(head == null) {
//If list is empty, both head and tail will point to new node
head = newNode;
tail = newNode;
}
else {
//newNode will be added after tail such that tail's next will point to newNode
tail.next = newNode;
//newNode will become new tail of the list
tail = newNode;
}
}
//display() will display all the nodes present in the list
public void display() {
//Node current will point to head
Node current = head;
if(head == null) {
System.out.println("List is empty");
return;
}
System.out.println("Nodes of singly linked list: ");
while(current != null) {
//Prints each node by incrementing pointer
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
public static void main(String[] args) {
SinglyLinkedList sList = new SinglyLinkedList();
//Add nodes to the list
sList.addNode(1);
sList.addNode(2);
sList.addNode(3);
sList.addNode(4);
//Displays the nodes present in the list
sList.display();
}
}
When you iterate through the linked list the first time, head points to the firstNode. Then as the while loop runs, the code updates the pointer("Current") to point to the next Node. This is shown where you see current = current.next; The loops keep running until current points to null, after which it ends. Hope you understand better.
You are right that head.next is not directly assigned. However, tail.next is. Let's see what happens in addNode() for two cases:
When the list is empty and you add a node, both head and tail are set to the newNode. Keep in mind that (this being Java) head and tail are references to the object newNode, that is, they reference the same object.
When there is already 1 element in the list, and you add a new node (the second one) you set tail.next = newNode. Now remember that head and tail are references to the same object (the first one added so far). They are basically two names for the same thing at this moment. So what really happens is that the object referenced by head and tail gets its next member set to newNode - and now both head.next and tail.next point to newNode. After that tail itself is made to reference tne newNode and at this moment head and tail start to reference different objects - head still referencing the first element, and tail now referencing the second (and so far last) element.
Now when you get to display(), you see that head is really a reference to the first element of the list, its next points to the second one and so on...

Generic Linked Lists find duplicates

Good day all,
I am studying Bsc-IT but am having problems.
With the current covid-19 situation we have been left to basically self-study and I need someone to put me in the right direction (not give me the answer) with my code.
I must write a program called appearsTwice that receives a linked list as parameter and return another list containing all the items from the parameter list that appears twice or more in the calling list.
My code so far(am I thinking in the right direction? What must I look at?)
public MyLinkedList appearsTwice(MyLinkedList paramList)
{
MyLinkedList<E> returnList = new MyLinkedList<E>(); // create an empty list
Node<E> ptrThis = this.head;//Used to traverse calling list
Node<E> ptrParam= paramList.head; //neither lists are empty
if (paramList.head == null) // parameter list is empty
return returnList;
if (ptrThis == null) //Calling list is empty
return returnList;
for (ptrThis = head; ptrThis != null; ptrThis = ptrThis.next)
{
if (ptrThis == ptrThis.element)
{
returnList.append(ptrThis.element);
}
}
Some issues:
Your code never iterates through the parameter list. The only node that is visited is its head node. You'll need to iterate over the parameter list for every value found in the calling list (assuming you are not allowed to use other data structures like hashsets).
if (ptrThis == ptrThis.element) makes little sense: it tries to compare a node with a node value. In practice this will never be true, nor is it useful. You want to compare ptrParam.element with ptrThis.element, provided that you have an iteration where ptrParam moves along the parameter list.
There is no return statement after the for loop...
You need a counter to address the requirement that a match must occur at least twice.
Here is some code you could use:
class MyLinkedList {
public MyLinkedList appearsTwice(MyLinkedList paramList) {
MyLinkedList<E> returnList = new MyLinkedList<E>();
if (paramList.head == null) return returnList; // shortcut
for (Node<E> ptrParam = paramList.head; ptrParam != null; ptrParam = ptrParam.next) {
// For each node in the param list, count the number of occurrences,
// starting from 0
int count = 0;
for (Node<E> ptrThis = head; ptrThis != null; ptrThis = ptrThis.next) {
// compare elements from both nodes
if (ptrThis.element == ptrParam.element) {
count++;
if (count >= 2) {
returnList.append(ptrParam.element);
// no need to look further in the calling list
// for this param element
break;
}
}
}
}
return returnList; // always return the return list
}
}

duplicate unsorted linked list

I've found this function to remove duplicate values in linked list:
public static void deleteDups (LinkedListNode n){
Hashtable table = new Hashtable();
LinkedListNode previous = null;
while(n!=null){
if(table.containsKey(n.data)){
previous.next = n.next;
} else {
table.put(n.data, true);
previous = n;
}
n = n.next;
}
}
Why is better copy the element in an hash table and not to another structure like a different linked list?
Thanks
Because checking for the existence of an item is an O(N) operation in a linked-list, however it is O(1) for the hash-table. Performance is the reason.
if(table.containsKey(n.data))
this is where the current item is checked if it is seen before (a duplicate) and that operation would be costly when implemented via a linked-list.

Adding to SortedLinkedList using nodes

im making a SortedLinkedList, I'm trying to add lets say 10 integers of different value so I can run some asssert tests. But I'm having a problem adding them so they are already sorted when they arrive to the LinkedList, I tried using the curr.info.compareTo(x) > 0 for instance, but I'm having trouble making the correct else/if statements so it sorts them when they are added.
This code has 4 classes, I can provide more if its unclear.
Thank you for your help in advance.
Best regards,
Victor
public class SortedLinkedList<T extends Comparable<T>> implements Iterable<T> {
/* Easy operations for a linked list
add(x): Searching for the place where the element x is to be added must
take place in the calling routine. This must set previous to
point to the node AFTER which the new element is to be inserted.
curr is set to point to the new element.
remove(): The curr element is removed from the list. Searching for this
element must take place in the calling routine. This must set
curr to point to the element to be removed. After removal curr
points to the element following the removed one.
isEmpty(): checks for an empty list
endOfList(): checks whether curr has reached and passed the end of the list
retrievecurr(): return the info part of the curr element.
reset(): resets the list so that curr points to the first element
succ(): an iterator, moves curr one step forward
Note that when a class implements the interface Iterable<T> then
it can be the target of the "foreach" statement. See IterationExample.java */
private Node start, curr, prev;
public SortedLinkedList() {
curr = null; // the curr position in the list
start = null; // the first element
prev = null; // the node before curr
}
public void add(T x) {
if (start == null) { // if start == null, insert a first element into an empty list
Node newNode = new Node(); // create the new element, info and link are set to null.
newNode.info = x; // and assign the data given as parameter. The link is left as null
start = newNode; // start is updated to point to the new element
curr = start; // curr is updated to point to the new first (and only) element
} else if (prev == null) { // a new first element is inserterd into a non-empty list
Node newNode = new Node(); // a new node is created ...
newNode.info = x; // and assigned the data given as parameter
newNode.link = start; // and linked before the old first element
start = newNode; // start is updated to point to the new first element
curr = newNode; // curr is updated to point to the new first element
} else { // a new element is inserted last (if prev.link == null) or between prev and curr
Node newNode = new Node(); // create a new node
newNode.info = x; // assign it the data given as parameter
newNode.link = prev.link; // link it before curr ...
prev.link = newNode; // ... and after previous
curr = newNode; // update curr to point to newNode
}
} // add*
}

Big-O for while loop?

How do I solve the Big-O for this problem containing a while loop that goes through the nodes and increment the length as long as it does not equal to null? Would this just be O(N) because it goes through N nodes? Also, the statements within the while loop would just be O(1), correct?
/**
*#param head the first node of the linked list
*#return the length of the linked list
*/
public static <E> int getLength(Node<E> head) {
int length = 0;
Node<E> node = head;
while (node!=null) {
length++;
node = node.next;
}
return length;
}
As you said the traversal of a linked list takes O(N) since you need to go over each node once.
The assignment operator is O(1), since you need to do this just once, every time.

Resources