Can't add item to the end of Linked list |
In your AddEnd function in the else clause, when you exit the while loop,
temp is now NULL. However, the element before it is still pointing to NULL.
Try something like
temp = *head;
if (temp->next == NULL) {
temp->next = new;
} else {
while((temp->next) != null) {
temp = temp->next;
}
temp->next = new;
}
in your else clause.
(This, and the apparent issue with your understanding of malloc referenced
by the others, new should be a Item * and the malloc call should be
malloc(sizeof(Item)). You also don't need to cast the return value of
malloc (indeed, there are some pitfalls that happen if you do).) Reading
your typedefs a little more closely, new should actually be an Item (since
it's a pointer to a List struct and you have typedef List* Item). T
|
Push and append an item into a linked list in C |
The problem was with the return type, i.e. the scope of a variable which in
this case is a pointer variable. mbratch also pointed out this, thank you
very much, but actually before reading mbratch's comment, I suddenly
remembered a point from a lecture note about "accessing an object outside
of its lifetime" which I think is different from "call by value/call by
reference" problem.
Just some clarifications for people who may run into this problem and may
get confused:
since we are allocating memory for the struct newNode INSIDE the function
pushToList (even though using dynamic memory allocation command), the
memory assigned to this variable would be free/destroyed when the function
ends and the control returns back to the callee function (in this case,
main()). So you should set the retu
|
Double-linked-list insert item algorithm flawed |
You probably got that from forgetting to set a previous or next ptr to
NULL.
Here I fixed the logic a little and got rid of the segfault (i tried to
comments as best as i could on what each case being checked is):
#include <iostream>
#include <string.h>
class doubled
{
private:
class sublink
{
private:
char data[30];
sublink *next_ptr;
sublink *previous_ptr;
friend doubled;
};
public:
sublink *first_ptr;
doubled(){first_ptr = NULL;};
void add_item(char *item);
void rm_item(char *item);
};
void doubled::add_item(char *item)
{
sublink *new_data;
new_data = new sublink;
strcpy(new_data->data, item);
// empty list case
if(first_ptr == NULL)
{
// Only item in the list, I have
|
linked list, need to delete all occurences of one given integer in linked list, i am not sure where i am going wrong |
Looks like you assign pointers a bit wrong when deleting elements inside
collection (not first one). Try to use assignment:
trailCurrent.link = current.link;
instead of just:
trailCurrent = current.link;
|
How do I change a singly-linked list to a doubly-linked list? |
You add an extra Node field to each Node that holds its previous Node
Insertion Pseudocode:
insert(Node n, index i) {
currentIndex = 0
currentNode = head
while (currentIndex < i) {
currentNode = currentNode.next
currentIndex++
}
n.prev = currentNode
n.next = currentNode.next
currentNode.next = n
}
|
How to show inner content in list item outside of that list item without being covered up by descending list items |
You must set the z-index of the clicked 'li' higher and in return the
former clicked 'li' back.
Here is the example: fiddle
And here the script:
var oldli;
$('li').click(
function(){
$(oldli).toggleClass('displayNone displayBlock');
$(oldli).css("z-index","1");
$(this).toggleClass('displayBlock displayNone');
$(this).css("z-index","5");
oldli=$(this);
}
);
|
Linked List inside a linked list with templates |
There are some issues in your addTeam function:
template<class data>
void LinkedList<data>::add(data a)
{
Node<data> *nodePtr;
nodePtr=new Node<data>(a);
// this should not be necessary, do that in the constructor of Node
nodePtr->setNextPointer(0);
if(head==0) // if head is empty
{
head=nodePtr; // make the new node the first node
// this is not necessary, nodePtr already has been set up above
// not to have a next node
// head->setPreviousPointer(0); // make the new node point to
null
}
else
{
// this check will never fail; what do you want to check here?
if(nodePtr==0) // if head is null
{
last=0; // if list unoccupied _last is null
}
|
Python list manipulation: Add an item to a string element to make it a 2 item list |
Modify a[0]:
>>> a = ['spam', 'eggs', 100, 1234]
>>> a[0] = [a[0], 'Devon']
>>> a
[['spam', 'Devon'], 'eggs', 100, 1234]
For your updated question:
>>> items = ['devon', 'baloney']
>>> a = ['spam', 'eggs', 100, 1234]
>>> a[0] = [a[0]] + items
>>> a
[['spam', 'devon', 'baloney'], 'eggs', 100, 1234]
If you're not sure about the position of 'spam' then use a list
comprehension:
>>> a = ['spam', 'eggs', 100, 1234]
>>> [item if item != 'spam' else [item, 'devon'] for item in a]
[['spam', 'devon'], 'eggs', 100, 1234]
|
WPF How to bind list to itemscontrol with each item being paired to a customcontrol and bound to the ith item in list |
The DataContext for each UI item in the ItemsControl will automatically be
assigned to the corresponding Data Item in the source Collection. Therefore
this is valid and will work:
<ItemsControl x:Name ="Signalviewer_Control" ItemsSource="{Binding
Source = {StaticResource signal_data}, Path = list_of_signals}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<wpfExp:SignalViewer Signal="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
|
Linked Lists in another Linked list |
In your function start, you are going through two List of type T.
But then, you're concatenating a whole list with a value of the other list,
while you're concatenating two lists in your Concat method.
Also, you are passing the parameters by copy, which probably not something
you want to do.
I think what you meant to do is something like that :
void Start(List< List <T> > & L, List<T>
&NewList)
Passing by copy means that your program send a copy of the parameter to
your function.
It means that the list you pass will be copied (which can be pretty heavy,
if your list is big), and that only the copy will be modified.
On the new version of the Start function that I gave you, you can notice
that I added &. It means that the value is passed by reference. B
|
Java linked list within a linked list |
What I would do is, instead of having a linked list of linked lists of
books, just have a linked list of late books within your user class. Then
you can add methods to add/delete books from the list as you see fit. This
approach makes more sense to me because the late books are essentially
owned by the user, and this way you don't have to keep track of a user's
late books by matching indices and tying them to another linked list.
|
Insert a linked list into another linked list |
You can start like this:
node *replaceChar(node *head, char key, char *str)
{
node *cur, prev;
for (cur = head, prev = NULL; cur != NULL; prev = cur, cur =
cur->next)
if (cur->ch == key) {
node *hstart = toString(str);
for (node *hend = hstart; hend->next != NULL; hend =
hend->next)
;
if (prev == NULL)
head = hstart;
else
prev->next = hstart;
hend->next = cur->next;
free(cur);
}
}
My assumptions:
Your node struct is like:
sturct node {
char ch;
struct node* next;
};
toString(str) works perfectly fine.
|
Moving a task from a backlog item to another |
Edit Sprints should contain PBIs not Tasks. Assuming you meant PBIs (which
contain Tasks) then here's a method for doing it in TFS 2013. Using the web
interface, you drag it. This assumes you have:
The left sidebar list of sprints is visible.
You are looking at the future sprint that contains the PBI to be moved.
You have expanded the twisty for the current sprint.
To do the drag you click anywhere on the PBI, say the Title, and hold a
moment. Move the mouse a bit and you'll see a ghostly rectangle
representing that item. You can continue the drag over to the future sprint
and release the right mouse button. The PBI and all of its tasks are moved
to the iteration path of the future sprint.
You can also edit the PBI and each Task in it, but that's tedious and slows
down the commitment
|
SQL: Get multiple line entries linked to one item? |
simple one:
select
"ITEMID",
case
when min("STATUS") in (4, 5) and max("STATUS") in (4, 5) then
'True'
else 'False'
end as requirements_met
from table1
group by "ITEMID"
better one:
select
"ITEMID",
sum(case when "STATUS" in (4, 5) then 1 else 0 end) as
MET_REQUIREMENTS,
sum(case when "STATUS" in (4, 5) then 0 else 1 end) as
NOT_MET_REQUIREMENTS
from table1
group by "ITEMID";
sql fiddle demo
|
jQuery UI sortable handles not moving item before 50% |
Use tolerance: 'pointer' like this:
$('ul').sortable({
handle: '.move',
tolerance: 'pointer'
});
Updated jsFiddle
|
Is there a way for one method to resolve itself before moving on to the next item in code |
You have two choices to achieve this:
Either return a value from your validate methods and check the value in
acitonPerformed. If validated then only move to the next method. You can
achieve this by putting few if/else statements
Or you can create validate exception classes. If your validate method is
not able to validate then it should throw an exception which you can catch
in your action performed. If you put all the validate method in the try
block then if a method throws the exception you can skip other methods as
you reach the catch block.
I am not sure whether I correctly understand your second problem. As I
understand you want to continue with the program even if your addFile
method throws an exception. For that case you need to wrap your addFile
method call in a separate try c
|
Merge two ordered linked lists into one ordered linked list |
Since you're checking if the NEXT value is null, when you hit your last
value, you'll break out of your merge while loop. Outside of this while
loop, you should just append the other list onto the other one. So if
List1 runs out of elements and List2 has 3 more, instead of walking through
List2, just make (end of List1)->next = (Where you left off in List2).
Also, don't return in the merge function. You don't need to. since yoru
lists already occupy space, you're just switching around where their
pointers are pointing. Once all the pointers are done, just return from
the function an access List1/List2 like you normally would (except you need
to figure out which List contains the first pointer, so just return 1 or 2)
also, you don't ever set merge to a value I don't think
|
deleting a node in linear single linked list given the start of the list |
if ptr is the first element in the list to delete, you set first to null,
not to the next of ptr. (sideeffect: you are not able to free the the rest
of the list)
your EDITH: delete should return the new Head, better make it a struct node
**first parameter which changes the first element if the first is the
deleted one
BTW: never cast the result of malloc.
BTW two. why use for-loop? everybody uses while-loop with linked lists
BTW three: normal variable names for linked lists are "head", "list",
"next", "prev", "last" with the nice side-affect, they are all the same
length, so making it neatly aligned.
|
Graphic item jumps to the end of path via QGraphicsItemAnimation without moving |
The QGraphicsAnimation class is deprecated. What you want is an adapter
between a QPainterPath and the animation system. See below for a complete
example.
Using painter paths for animations requires some extra smoothing
(resampling) as there will be velocity changes along the path, and it won't
look all that great. You may notice it when you run the code below. Painter
paths are meant for painting, not for animating stuff.
The extent of this misbehavior will depend on the kind of path you're
using, so it may end up working OK for the particular use case you have.
#include <QApplication>
#include <QAbstractAnimation>
#include <QPainterPath>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsEllipseItem>
#include <QDebug>
class
|
SQL reformat a linked list (a list of locations: nodes -> edges) |
Try following query.it will work properly .
WITH TEMP
AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY ID2 ORDER BY ID1) AS ID , *
FROM LOCATION
)
SELECT A.ID1, A.ID2 , B.LOCATION , A.LOCATION
FROM TEMP AS A LEFT OUTER JOIN TEMP AS B ON A.ID -1 = B.ID AND A.ID2 =
B.ID2
UNION ALL
SELECT A.ID1,A.ID2 , A.LOCATION , NULL
FROM TEMP AS A
WHERE PATHTYPE = 'FINISH'
ORDER BY ID1
sqlFiddle
|
Quick way of selecting a random item from a list - with varying probabilities based on item value? |
You've already got the basic idea - sum the weights (which happen to be the
same as your values here) and take a random number in that range - although
I'd use 0 as the lower bound, and the sum as the exclusive upper bound.
Then you just need to work through the list to find out which value that
corresponds to... begin at the start of the list, and keep checking whether
the random number is less than the current item's weight: if it is, that's
the selected item. If it isn't, subtract the weight from the random number,
and move on.
That's an O(N) algorithm, admittedly. If you need to take a random number
from the same list multiple times, you could build an accumulated weight
list, and then do a binary search to find out which index corresponds with
which random number... but I'd stick to
|
PHP/MYSQL, removing an item from a list from a joining query, without deleting the item from the table.? |
Without seeing your db schema, very difficult to guess. But it might look
something like this:
DELETE FROM `order`
WHERE orders.productID = 456
AND orders.orderID = 123
|
MongoDB with update queries, create and add item to list or increase item's counter |
You need to do two things:
Use the {upsert:1} flag on update to insert particular date document if it
doesn't already exist.
Use {$inc} operator to increment your item values. It turns out that if
you increment a field that doesn't exist by 1 it will be created with value
1 (it's as if it existed with value 0).
You may not be able to get the above accomplished with the schema you
currently have. In order to increment a counter it has to be the name -
i.e. "a":1, "b":17, etc. You currently have it as key:"name",
counter:"value" which means you can only update them with positional
operator. But positional operator requires that you match an element in
order to successfully update it, so there goes the strategy to use $inc
So it looks like if you want to do this in a single update st
|
PHP drop-down list with main item as optgroup and child item as option |
You are referencing to $rs_pa['ID'] on this line:
$mysql_select_child = "SELECT * FROM $mysql_table_items WHERE `Parent`
= '" . $rs_pa['ID'] . "' AND Active = 1 ORDER BY `Order` ASC";
Are you sure $rs_pa['ID'] is defined at that point?
Something like this should work better:
$mysql_table_items = "sys_menu_top";
$mysql_table_options = "sys_options";
// SQL QUERY
$mysql_result_number = mysql_query("SELECT VALUE FROM
$mysql_table_options WHERE Name LIKE 'nav_menu_elements_on_line_usr'") or
die($myQuery . "<br/><br/>" . mysql_error());
$mysql_select_parent = "SELECT * FROM $mysql_table_items WHERE `Parent`
= '0' AND Type LIKE 'top' AND Active = 1 ORDER BY `Order` ASC";
// SQL RESULT
$mysql_result_number = mysql_fetch_array($mysql_result_number, MYSQL_ASS
|
itemsingletap on list is not detected when 1 item is tapped followed by swiftly tapping a different item? |
Check this its working for me.
config : {
refs : {
navigationview : 'navigationview',
},
control : {
'productTable dataview[id=productDataView]':{
itemsingletap : 'onProductItemTap'
}
}
},
onProductItemTap: function (list, idx, target, record, evt) {
Ext.Msg.alert('itemsingletap', record.data.Content);
Ext.select('#resultID').elements[0].innerHTML = record.data.Content;
},
|
Ruby on Rails: Foursquare remove list item gives 400 value is invalid for item id |
One thing I'd try is to build the URL programmatically using Ruby's
built-in URI class:
require 'ostruct'
require 'uri'
#
# set up some variables just for example values
#
list = OpenStruct.new('id' => 'some_list_id')
item = OpenStruct.new('foursquare_id' => 'some_foursquare_id')
ENV['FOURSQUARE_TOKEN'] = 'foo'
uri = URI.parse("https://api.foursquare.com/v2/lists/#{ list.id
}/deleteitem")
uri.query = URI.encode_www_form(
'itemId' => item.foursquare_id,
'oauth_token' => ENV['FOURSQUARE_TOKEN'],
'v' => 20120321,
)
uri.to_s
=>
"https://api.foursquare.com/v2/lists/some_list_id/deleteitem?itemId=some_foursquare_id&oauth_token=foo&v=20120321"
The reason this is a good idea, is that some values have to be encoded in a
URL. Simply shoving them into a string wo
|
Android ListView select item and show information about list item |
For the information you can use this code for the dialog box and this can
be called by showSettingsAlert(); wherever you want this dialog box to
displayed.
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
// Setting Dialog Title
alertDialog.setTitle("Title here");
// Setting Dialog Message
alertDialog.setMessage("here the information can be display");
alertDialog.setNegativeButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
for the other thing look Contextual Action Mode. these li
|
Always show bootstrap drop down list item, when that item is clicked or navigated to |
Right, I'll preface this by saying that I couldn't get it to work properly
in jsfiddle because it doesn't reload the page when the named links are
clicked however, I believe this should help
$('.dropdown-menu li a').each(function() {
if($(location).attr('href').indexOf($(this).attr('href')) > 0) {
$('.dropdown-menu').show();
}
});
So what we're doing here is checking the link href on each list item and
checking if it is contained within the page link. If any of them are
matched, the dropdown will be set to show. Since bootstrap uses visibility
and show() uses display:block, the show() should override the visibility:
hidden when you stop hovering
See how you go - you might need to modify it slightly for your own purpose
http://jsfiddle.net/yZ8C6/1/
You can get the
|
Editing list Item using drop down menu bootstrap when clicking on an item |
Use this JavaScript code:
$(function() {
$('#changeEN').hide();
$('.newDropdownLanguage li').click(function(e) {
e.preventDefault();
$('#current-language').text($(this).text());
$('.newDropdownLanguage li').show();
$('#changeEN').show(); // Actually it should work without this line,
but I don't get why it is not working.
$(this).hide();
});
});
Don't forget to add one <li> for English:
<li><a id="changeEN" href="#">English</a></li>
|
How to select first item of a list in and render the page during initial load for the first selected item |
That's easy. in your AssetSummaryPageModel-Bean you will add a new method
with the @PostConstruct annotation so it will be called after the bean has
been constructed. In this method you will set selectedSensorId to the first
item of your childFacilitySelectionList.
When your page is being rendered, JSF will see that a value was already
selected and will set this one as the selected one.
@PostConstruct
public void init() {
selectedSensorId = childFacilitySelectionList.get(0);
}
|
How to Find value in Text of list item by entering id or serial of item |
You can create an index like:
var index = {'101-01-071-02':0,'101-14-001-01':1,'106-01-002-01':2};
Then you can find the LI something like:
var value = '106-01-002-01';
var lis =
document.getElementById('AllProducts').getElementsByTagName('li');
if (value in index) {
var theOne = lis[index[value]];
}
Note that getElementsByTagName returns a live NodeList, so you can get the
collection once then modify the list of LIs in the DOM all you like, the
collection will always reflect the LIs that are the descendants of
"AllProducts".
You could also use an array with indexOf.
Edit
Here's a fiddle that does the job: http://jsfiddle.net/jPKtz/. It builds
the index, selects the product if the product serial number is correct, and
clears previous entries.
|
How to remove item from generic list that relates to item in listbox? |
What you want to do is bind your ListBox to you List of employees. This
post shows the binding and the comments shows the removing code as well.
The idea is that when you remove an item from the DataSource, then you
won't see it in the ListBox.
Binding Listbox to List<object>
The problem with the DeleteRecord() method is that the lstRecords object
you just created isn't the ListBox that is on the form.
|
Compare item to list of items, excluding the item being compared |
if (RadUpload1.UploadedFiles.Count > 1)
{
for (int fileBuffer = 0; fileBuffer <
RadUpload1.UploadedFiles.Count-1; fileBuffer++)
{
for (int fileList = fileBuffer + 1; fileList <
RadUpload1.UploadedFiles.Count; fileList++)
{
if (RadUpload1.UploadedFiles[fileBuffer] !=
RadUpload1.UploadedFiles[fileList])
{
//....
|
Client Object Model call context.executeQueryAsync: After adding an item to a list, cant open the new item until the onQuerySucceeded completes? |
Update: The Edit Task dialog now opens the item as expected. I am not
sure why. I may have changed a list setting related to email notifications
on change of assignment.
HTH
/bac
|
How to keep dynamic item behavior after clicking any item in the list? |
You are adding the class hoverblock to all the li elements when you click
on a link. The hover handler is written to ignore li.unrun_tab elements
that have the hoverblock class.
If you want the hover behavior to persist after you have clicked on an item
in the product list, you have to either remove the code in your click
handler that adds the hoverblock class, or remove the code in your hover
handler that excludes class '.hoverblock` from hover processing.
It's a bit unclear what you want the behavior to be. What you are
describing seems to be that you want a click on a product to do nothing
with respect to the adjacent images.
|
How do I grab a value of an item in a List of Tuples based off of a value from another item? |
This is a fairly simple operation with LINQ. The first step is to order the
list by DateTime (Item3), after that you can just chain First() on the
query and it will return the most recent item. Note that LINQ operations
are not done in place, meaning the order of itmes in myList will not be
affected by this operation. It will create a new IEnumerable that is order
by tuple.Item3 then give you the first item from that.
Tuple<string, string, DateTime> mostRecent = myList.Orderby(x =>
x.Item3).First();
To add a restriction on group you simply need to add a where clause.
Tuple<string, string, DateTime> mostRecent = myList.Where(y =>
y.Item2 == "Programmer").Orderby(x => x.Item3).First();
I'd recommend checking out the docs on the LINQ to Objects query operators.
Ever
|
C# how to find item which item is clicked in a list? |
Try using LINQ:
this.drivers.Where(d => d.Name == name).ToList().ForEach(delegate(Driver
d)
{
// Do something
});
If the names are unique, this will be easier to use:
var driver = this.drivers.Single(d => d.Name == name);
// Do something with driver
Alternatively, you can use a loop:
foreach(var d in this.drivers)
{
if(d.Name == name)
{
// Do something
}
}
If your items will always be ordered "1W","2W",..., those will help you
identify the index:
var index = int.Parse(name[0].ToString()) - 1; // e.g. "3W"[0].ToString() =
"3"
var driver = this.drivers[index];
// Do something
|
Pop from Linked-list |
Your need to pass the address of head for your function to modify it. Then
your function needs to dereference this address. Further, the last pop()
needs to change *AddressOfHead as well
Node *pop(Node **AddressOfHead) {
Node *temp = *AddressOfHead;
if (temp) {
*AddressOfHead = temp->next;
}
return temp;
}
...
// Usage example
Node *TopOfList = pop(&Head);
|
constructor for a linked list |
Typically, head and tail will be null pointers for an empty list so
dereferncing them like this:
head->previous = NULL;
will be undefined behaviour.
The constructor would simply be:
List::List() : head(0), tail(0), count(0) {}
(or use nullptr for head and tail if your C++ is advanced enough).
If your the type of person who likes dummy nodes at the start and end of
your lists, you will need to allocate them before trying to use them:
List::List() : count(0) {
head = new somethingOrOther();
tail = new somethingOrOther();
head->previous = NULL;
head->next = tail;
tail->previous = head;
tail->next = NULL;
}
This trick is often used to greatly simplify list insertions and deletions
since you never have to worry about whether you're insertin
|
Linked list within a structure |
There are multiple issues, to start with
callLog = malloc(dataRow+1 * sizeof(callLog));
change it to
callLog = malloc(dataRow+1 * sizeof(*callLog));
Either initialize callLog[0].outBoundLegs to 0 as
memset(callLog[0].outBoundLegs, 0, sizeof(*callLog[0].outBoundLegs)) or use
calloc()
callLog[0].outBoundLegs = calloc(1, sizeof(node));
callLog[0].outBoundLegs->target = "0";
Don't initialize strings that way, do
callLog[0].outBoundLegs->target = strdup("0");
However, remember to free the memory when appropriate.
|