Adding to SortedLinkedList using nodes - linked-list

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*
}

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
}
}

Unable to get children of IContent

I'm trying to get the Children of an Icontent object.
IContent filialsParent = cs.GetById(filialParrentId);
if (filialsParent != null)
{
IContentService contentService = Umbraco.Core.Composing.Current.Services.ContentService;
bool hasChildren = contentService.HasChildren(filialsParent.Id);
long totalChildren;
IEnumerable<IContent> children = contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren);
foreach (var child in children)
{
context.WriteLine(string.Format("child: {0}", child.Name));
}
context.WriteLine(string.Format("Children found:({0}) in: {1}", children.Count(), filialParrentId));
}
If I debug the code, I get the following.
My long totalChildren will be 1 after the line contentService.GetPagedChildren(filialsParent.Id, 1, 100, out totalChildren); runs.
My IEnumerable<IContent> children is null, and for that reason (of course) is my children.Count() 0
Sadly filialsParent does not contain the function .children() as I hoped it would.
Is there a way to get the Children of my filialsParent, and yes it does have children that are published.
I dit got the exact same problem. For testing purposes I removed everything Only bare essentials.
==> umbraco 8.0.2
Make sure you got a parent and a few childeren attached
// For testing purposes hardcode your parent Id
var contentId = [ID];
// SET for returning total records
long totalChildren;
// int id ==> You even could hardcode your first param (contentID in here)
// long pageIndex ==> SET your index to 0 ==> first indexpage starts at 0 and not 1 ==> if you set this to 1 and the Pagesize = 100 and you have only 99 childeren you wil wil get null because we are requesting the second page
// int pageSize ==> We need max 10 childeren
// out long totalChildren
// IQuery<IContent> filter = null ==> not used
// Ordering ordering = null ==> not used
IEnumerable<IContent> children = Services.ContentService.GetPagedChildren(contentId, 0, 10, out totalChildren);

How do I join two linked lists in C?

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

How do i select a record in a grouped smartgwt listgrid?

I have site with a listgrid and a openlayers map with points. When i cklick on one of these, the application shall scroll and mark this record. This works with a standard listgrid, but with a grouped listgrid it does not work.
lg = new ListGrid();
lg.setWidth(330);
lg.setDataSource(ds1);
lg.setAutoFetchData(true);
lg.setSortField("KU_NAME");
lg.setGroupStartOpen(GroupStartOpen.ALL);
lg.setGroupByField("KU_NAME");
lg.setShowFilterEditor(true);
kuName = new ListGridField("KU_NAME", "Künstler Name",150);
// Standorte
ListGridField stdOrt = new ListGridField("STDORT_NR","Standort Nr.");
ListGridField oid = new ListGridField("OID","OID.");
lg.setFields(stdOrt,kuName,oid);
and the select:
String stdortOID = stdOrtOIDjso.toString();
ListGridRecord[] records = lg.getRecords();
int i;
for (i = 0; i < records.length; i++) {
if (records[i].getAttribute("OID").equalsIgnoreCase(stdortOID)){
break;
}
}
lg.deselectAllRecords();
lg.selectRecord(i);
lg.scrollToRow(lg.getRecordIndex(record));
the reason is that in the record is only the value of the group name and the other attributs are unavailable.
When grouping is enabled, all data are "transformed" into tree and listgrid itself contains data for groups so you have to look for your record in this tree. Replace last 3 lines with (modified) Vittorio Paternostro suggestion:
Tree tree = lg.getGroupTree();
if (tree != null) {
TreeNode node = tree.find("OID", stdortOID);
if (node != null) {
lg.selectSingleRecord(node);
lg.scrollToRow(getRecordIndex(node));
lg.markForRedraw();
}
}
Note: Instead of deselectAllRecords + selectRecord use simplified selectSingleRecord.
I had the same need and the following works fine for me. You can use getGroupTree() and search the desired property in it (column value) without worrying about grouping. Make sure you search for unique values (i.e. a unique key) to identify a precise node.
Tree tree = getGroupTree();
if (tree != null) {
TreeNode node = tree.find("property", "value");
if (node != null) {
selectSingleRecord(node);
scrollToRow(getRecordIndex(node));
markForRedraw();
}
}

Resources