#include <iostream> #include <cstdio> #include <math.h> using namespace std; struct list { int item; list *next; public: list() {} list(int val, list *Next) : item(val), next(Next) {} }*head = NULL; list *lastItem(list *head) { if (head == NULL) return 0; else { while (head->next != NULL) head = head->next; } return head; } void pushBeginning(list **head, int data) { *head = new list(data, *head); } void pushEnd(list **head, int number) { if (*head == NULL) { *head = new list(number, *head); } else { list *last = lastItem(*head); last->next = new list(number, last->next); } } void delStart(list *head) { list *tmp = head->next; list *current = head; delete current; head = tmp; } void delEnd(list *head) { list *last = lastItem(head); list *tmp = head; while (tmp->next != last) tmp = tmp->next; tmp->next = last->next; delete(last); head = tmp; } void show(list *head) { if (head) { cout << head->item << ' '; show(head->next); } else cout << '\n'; } int main() { //head = new list(); //list *head = NULL; pushBeginning(&head, 1); pushEnd(&head, 1000); pushEnd(&head, 1); pushEnd(&head, 15); pushEnd(&head, 150); show(head); delEnd(head); show(head); delStart(head); show(head); return 0; }
Closed due to the fact that off-topic participants are free_ze , pavel , Kromster , Streletz , aleksandr barakin 2 Sep '16 at 6:30 .
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
- “Questions asking for help with debugging (“ why does this code not work? ”) Should include the desired behavior, a specific problem or error, and a minimum code for playing it right in the question . Questions without an explicit description of the problem are useless for other visitors. See How to create minimal, self-sufficient and reproducible example . " - pavel, Kromster
|
1 answer
because function
void delStart(list *head) { list *tmp = head->next; list *current = head; delete current; head = tmp; }
accepts a pointer that remains to be pointed to where it is and pointed to before the call, since the address of the pointer is copied to the function, the original does not change. You need to pass a pointer to a pointer, that is:
void delStart(list **head) { list *tmp = *head->next; list *current = *head; delete current; *head = tmp; }
|
head
local global? - paveldelStart
or pass alist **head
or don’t transmit anything at all. - pavel