Traversing a singly list - linked-list

While traversing a singly list, inside the loop condition, whats the difference between temp != NULL and temp-next != NULL? For Ex
while(temp != NULL)
{
......
......
}
and
while(temp->next != NULL)
{
......
......
}
I don't understand the difference between the two.

From context this answer assumes that temp is a node in the linked list.
temp->next != NULL returns true when there is a node after temp (i.e. when temp is not the last node in the list). As an example, consider this list:
a -> b -> c -> NULL
if we do temp = a->next then temp is b, and temp->next != NULL evaluates to true since c (not NULL) comes after b.
temp != NULL returns true when temp itself is a node in the list. This might not be the case if, for some reason, you have traversed too far down the list. Using the same list as above: if we do temp = c->next, then temp != NULL evaluates to false.
Understanding that, the difference between the lists is as follows:
while(temp != NULL)... executes until temp is NULL
while(temp->next != NULL) executes until the node after temp is NULL

Related

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

what is the difference between n != null and n.next != null in linkedlist?

When writing a while loop to iterate through a linkedlist, what is the difference between using while(n != null) and while(n.next != null)? n being the head of the linkedlist.
while(n!=null) will traverse the entire list for printing nodes value or counting number of nodes.
while(n.next!=null) will stop at the tail (last node) of the linked list.

ActiveRecord Query on text field PostgreSQL

I have a table Products and around 58000 records in it. I run two queries are as follows.
Product.where(description: 'swiss').count
It returns 0 products out of 58000 products. But when I run query below.
Product.where.not(description: 'swiss').count
it returns 2932 products out of 58000 products. I think it should return all 58000 products, because it is the reverse of first query.
I did not understand why it returns only 2932 products.
If you have NULL values in your columns, this could happen, because NULL always compares as NULL, even to itself, but WHERE expression must be true to include a result.
'a' = 'a'; True
'a' = 'b'; False
'a' = NULL; Results in NULL (not false!)
NULL = NULL; Results in NULL (not true!)
'a' != 'a'; False
'a' != 'b'; True
'a' != NULL; NULL
e.g. consider the table null_test containing
id | str
----+-----
1 | <NULL>
2 | a
3 | b
When looking for a column equal to some value, the NULL is never equal, so this will just return row 2.
SELECT id FROM null_test WHERE str = 'a';
But the same applies looking for a column not equal to some value, the NULL is never not equal (its NULL), so this will just return row 3.
SELECT id FROM null_test WHERE str != 'a';
Thus the total of your = and != is not all the rows, because you never included the NULL rows. This is where IS NULL and IS NOT NULL come in (they work like you might expect = NULL and != NULL to work).
SELECT id FROM null_test WHERE str != 'a' OR str IS NULL;
Now you get rows 1 and 3, making this the opposite of str = 'a'.
For ActiveRecord, it treats the Ruby nil value like the SQL NULL and creates the IS NULL checks in certain situations.
NullTest.where(str: 'a')
SELECT * FROM "null_test" WHERE "str" = 'a'
NullTest.where.not(str: 'a')
SELECT * FROM "null_test" WHERE "str" != 'a'
NullTest.where(str: nil)
SELECT * FROM "null_test" WHERE "str" IS NULL
NullTest.where.not(str: nil)
SELECT * FROM "null_test" WHERE "str" IS NOT NULL
NullTest.where(str: nil).or(NullTest.where.not(str: 'a'))
SELECT * FROM "null_test" WHERE "str" IS NULL OR "str" != 'a'
You have likely many records where description is nil and those are not included in the not.
A way to include the 'nil' records as well would be...
Product.where('description <> ? OR description IS NULL', 'swiss')
Or alternatively
Product.where.not(description: 'swiss').or(Product.where(description: nil))

Entityframework query, only select if variable is not null else don't select

I have this kind of query:
var p = form p in db.table
where(p.Id == variable1 && p.proId == variable2 ...)
select p.Tolist();
and for eg. if variable 1 is null don't compare that condition in where clause just take the where clause
where (p.proId == variable2 ...)
Is there any way to do this . Thanks in advance.
Just simple like this:
where((variable1 == null || p.Id == variable1) && p.proId == variable2 ...)
Can't you just null check in the where clause?
where((variable1 == null || p.Id == variable1)
&& (variable2 != null && p.proId == variable2))
While the other answers here will work, you tagged your question entity-framework, and anytime you're writing LINQ-to-Entities, it's very important to have your IQueryable/IEnumerable boundary firmly in mind, because only fully IQueryable compliant code is efficiently convertible to SQL (and many times, e.g., string.Format, is not convertible at all).
var q = null != variable1
? from p in db.table
where p.Id == variable1
where p.proId == variable2
select p
: from p in db.table
where p.proId == variable2
select p;
Note that, if writing LINQ-to-Objects instead, the other answers given are much more efficient, concise, and readable:
var q = from p in someEnumerable
where null == variable1 || p.Id == variable1
where p.proId == variable2
select p;
Note: I left off the .ToList() to keep the query as an IQueryable (or IEnumerable) because there are so many times you actually wish to enumerate through the query only once, or project to something simpler before resolving the query (e.g., select p.Id). This is especially important in the case of L2E, because everything you do before the .ToList() (or .ToArray() or .Load()) is directly convertible to SQL, which is the most powerful way to use EF.

Web form for creating custom filters with boolean logic

I have a Rails application in which I'd like a user to be able to create custom boolean combinations from a list of categories, which is itself dynamically loaded. For example, if I have the categories foo bar and baz, I would like the user to be able to select (foo AND bar) OR baz or foo OR baz or any other logical combination of those categories. The most common use case I anticipate is something like (a OR b OR c) AND (d OR e OR f) AND (g OR h); that is, a conjunction of several disjunctions.
The results would then be stored in some data structure which could be later used as a filter. Ideally this would all be done through a graphical interface, rather than having the user construct the boolean logic in text.
Before I attempt to implement this myself, is there a library that I can pull in that already implements this or something similar? Or something open-source that could get me part of the way there, and that I could fork and modify?
You could implement a Boolean Retrieval with four ways to select a given category:
not selected
positive selected (+ prefix; category is mandatory)
negative selected (- prefix in Google search; category must not occur)
selected (no prefix)
Not in ruby-on-rails but probably easy to translate from c#:
public bool IsMatch(string s)
{
s = s.ToLower();
bool ret = ((negWords.Count == 0) || !hasMatchInSet(s, negWords, true))
&& ((posWords.Count == 0) || hasMatchInSet(s, posWords, false))
&& ((words.Count == 0) || hasMatchInSet(s, words, true));
return ret;
}
private bool hasMatchInSet(string s, HashSet<string> setOfWords, bool breakOnFirstMatch)
{
int matches = 0;
bool ret = false;
foreach (string w in setOfWords)
{
if (s.IndexOf(w, StringComparison.InvariantCultureIgnoreCase) >= 0)
{
matches++;
if (breakOnFirstMatch)
{
break;
}
}
}
ret = (breakOnFirstMatch && (matches > 0)) || (matches == setOfWords.Count);
return ret;
}

Resources