![]() An alternative could be to have the function return a pointer to the new head: struct node push (struct node head, int data) struct node head NULL head. when push-ing a new element to the list you want to insert the element in the front and therefore need to change the value of head. See the other answers for a complete and correct code for adding new nodes in an empty and non-empty list. The first version is probably what you want, i.e. To add a new node you can technically add it anywhere but it is usually added at the end (at least from what I've seen). Now whenever we will call the push() function a new node will get added to our list in the front, which is exactly how a stack behaves. Once you figure out how next/prev should be set then translating that into code should be relatively straight forward. Draw out a list on paper with next/prev arrows and see how they need to be changed when adding nodes to an empty/non-empty list as well as how to delete and move nodes around. I would suggest taking a step back from the code for a bit to ensure you properly understand the concepts behind a doubly-linked list. At the moment you are leaking memory and if you try to delete nodes you'll likely result in a double-free and crash. A collection structure represents a sequence of nodes. ![]() What is a Linked List Before we start to discuss, we need to formulate a clear understanding of what a linked list is. While you don't show it in the example, you'll eventually need a destructor as well as a copy operator and copy constructor (the rule of three). When and where is used Code implementation and complexity analysis.The addition of a node into a non-empty list is also incorrect.In a well formed double-linked list then last->next should always be null, as should first->previous.The setting of next/previous in first/last doesn't make any sense either. first->next is left undefined and why are you creating two nodes, both first and last? In a list with one element then first = last. The addition of a node to an empty list is not correct. The Push() function is used to insert data, but before inserting we need to check wheteher the stack is full or not because if the stack is already full we.Either add a constructor to node or ensure they are initialized after allocation. ![]() Function Call: push local environment and return address.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |