Adding List Items or Nodes in Linked List

adding Objects to a linked list

Your Wagon should not point to the next Wagon. Create an inner class Node in the LinkedList<T> class that has a next pointer as well as others. The Node class should be something like the following:

class Node  {
T object;

Node next;
Node previous; // optional depending on linked list type.
}

The LinkedList would be of type Wagon.

E.g. LinkedList<Wagon> list = new LinkedList<>(); and the Wagon instance would be placed in the object field of the node.

How to add a node to a linked list?

Try this:

class LN:
def __init__(self, value):
self.value = value
self.next = None

def insert_ordered(root, data):
node = LN(data)
if root == None:
return node
else:
if root.value > data:
node.next = root
return node
else:
temp, prev = root, None
while temp.next and temp.value <= data:
prev = temp
temp = temp.next

if temp.next == None and temp.value <= data:
temp.next = node
else:
node.next = prev.next
prev.next = node

return root

root = None
root = insert_ordered(root, 4)
root = insert_ordered(root, 7)
root = insert_ordered(root, 9)
root = insert_ordered(root, 14)
root = insert_ordered(root, 12)
#4->7->9->12->14

Inserting at head of linked list?

Add these lines at the end of your head_insert() function definition:

if (list->head == NULL)
{
list->tail = newHead;
}
list->head = newHead;

In your function, after adding new node at head the struct LinkedList still pointed to the previous head. You should change that head to the newly inserted head. And if there was no nodes in the list you should also set the newly created head
Here is the full function.

void head_insert(LinkedList *list, int data)
{
node *newHead = create_node(data);
newHead->next = list->head;
if (list->head == NULL)
{
list->tail = newHead;
}
list->head = newHead;
}

How can I add the second item in the linked list without overwriting the first one?

Here, you seem to overrwrite the data at self.iterator. Rather, you should set the data to the new node you created:

self.iterator.data = value

Fixed code:

class LinkedList:
def __init__(self):
self.head = Node()
self.iterator = self.head

def isEmpty(self):
if self.head.data is None:
return True

def insert(self, value):
if self.isEmpty():
self.head.data = value

else:
while self.iterator.next is not None:
self.iterator = self.iterator.next
new_node = Node()
new_node.data = value
self.iterator.next = new_node
self.iterator = self.head

Re-order single linked list if elements have been searched?

I suppose you should do it like this:

public class SearchLinkedList<E> {
private Node<E> first;

public static void main(String[] args) {
SearchLinkedList<Integer> list = new SearchLinkedList<Integer>();

list.insert(1000);
list.insert(2000);
list.insert(3000);

System.out.println(list.getFirst());

System.out.println(list.find(3000));
System.out.println(list.getFirst());
list.insert(4000);
System.out.println(list.find(200));
}

public SearchLinkedList() {
first = null;
}

public void insert(E e) {
if (first == null) {
first = new Node<E>(e);
} else {
//while(temp.next.searched == true) then insert new Node where the next node is null or searched == false
Node<E> temp = first;
while (temp.next != null && temp.next.searched) {
temp = temp.next;
}
Node<E> node = new Node<>(e);
if (temp.next != null) {
node.next = temp.next;
}
temp.next = node;
}
}

public E getFirst() {
return first.data;
}

public E find(E x) {
if (first == null) {
return null;
} else {
//while (temp != null) if node found set it's searched = true and move it to front of list
Node<E> temp = first;
while (temp != null) {
if (temp.data.equals(x)) {
temp.searched = true;
break;
}
temp = temp.next;
}
if (temp == null) return null;

pushForward(temp);
return temp.data;
}
}
//Find pre-linked node with our node, bind our node with parent next node
//and link parent with node.
private void pushForward(Node<E> node) {
if (first == null || first.next == null) return;
Node<E> temp = first;
while (temp.next != null) {
if (temp.next.equals(node)) {
temp.next = temp.next.next;
node.next = first;
first = node;
break;
}
temp = temp.next;
}
}

private static class Node<E> {
private E data;
private boolean searched;
private Node<E> next;

private Node(E e) {
data = e;
searched = false;
next = null;
}
}

}

Also you could mix pushForward and find methods to make find to do what you want by one iteration through the list (O(n)), because O(n^2) there.
Might be helpful: https://www.geeksforgeeks.org/java-program-for-inserting-node-in-the-middle-of-the-linked-list/

Remove last node of a linked list, and add this to another linked list

For some reason I can not get my pointers right, well.. atleast that is where I think the problem lays.

You're right, but it's a little more than that. For example, after struct Node *head = NULL; nothing modifies the value in head, so every time you do head->next you're accessing memory at "NULL + a small offset" (and will probably crash).

To remove the last entry from a singly linked list, you have to find the entry before the last entry (so that you can modify its next); and to add an entry to a linked list you have to find the last entry (so that you can modify its next). With this in mind we can break it into 5 parts:

  • Do sanity checks

  • Find the entry before the last entry in the *cards list

  • Remove the last entry in the *cards list

  • Find the last entry in the *column list

  • Add the (removed) entry to the end of the *columns list

You can implement each of these 5 pieces one at a time (and test them). This is an important part of programming - breaking more complex stuff into simpler easier things.

The resulting code might look something like (untested):

void movenode(struct Node **cards,struct Node **column) {
struct Node *temp = *cards;
struct Node *removed;

// Do sanity checks

if (temp == NULL) {
return;
}

// Find the entry before the last entry in the `*cards` list

if(temp->next != NULL) {
while(temp->next->next != NULL) {
temp = temp->next;
}
}

// Remove the last entry in the `*cards` list

if(temp == NULL) {
// The last entry was the first entry
removed = temp;
*cards = NULL;
} else {
removed = temp->next;
temp->next = NULL;
}

// Find the last entry in the `*column` list

temp = *column;
if(temp != NULL) {
while(temp->next != NULL) {
temp = temp->next;
}
}

// Add the (removed) entry to the end of the `*columns` list

if(temp == NULL) {
// There was no last entry (list was empty)
*column = removed;
} else {
temp->next = removed;
}
}

Calling a linked list

well if you looking for internal boilerplate, below is code for that.

here you need to create classes for nodes, linked list and solutions,.

then with the given number, you need to create a linkedlist object.
this above part is done in leetcode by themself and this object is passed to class Solution method middleNode, where OP code run and give result. next once output is got it is compared with existing solution

# Node class for individual nodes
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

# linked list class, to create a linked list of the list nodes
class LinkedList:
def __init__(self):
self.head = None
# adding a node element to linked list
def add(self, node):
if self.head is None:
self.head = node
else:
curr = self.head
while curr.next:
curr = curr.next
curr.next = node
curr = node
# printing element of existing linked list
def print_ll(self):
curr= self.head
while curr:
print(curr.val)
curr= curr.next

# leetcode solution class
class Solution:
def middleNode(self, head) :
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow

# value with which we create list nodes
values = [1,2,3,4,5,6,7,8,9,10]

ll = LinkedList() # create a linked list class object
for i in values:
node = ListNode(i) # creating a list node
ll.add(node) # adding list node to linked list
#ll.print_ll() # printing linked list

x = Solution().middleNode(ll.head) # passing linked list object to leetcode solution method and getting result

while x: # printing result
print(x.val)
x=x.next


Related Topics



Leave a reply



Submit