int main(){
IntSLList list1,list2;
list1.addToHead(1);
list1.addToHead(2);
list1.addToHead(3);
list1.printAll();
IntSLLNode *p;
list1.assignvalues(p);
//p....p->next...p->next->next
//p refers to the first node of the linked list
return 0;
}
IntSLList* IntSLList::deletelast(IntSLLNode *p)
{
if(p==NULL || p->next ==NULL)//check this one as my base case
{
return NULL;
}
else
{
p->next = deletelast(p->next);
}
}
void IntSLList::assignvalues(IntSLLNode *p)
{
p=head;
}
有人知道我在这里做错了什么吗?它说p->next
具有错误的数据类型,因为它是......
答案 0 :(得分:3)
试试这个:
int main() {
IntSLList list1;
list1.addToHead(1);
list1.addToHead(2);
list1.addToHead(3);
list1.deletelast(list1->head);
list1.printAll();
}
void IntSLList::deletelast(IntSLLNode *p){
if (p->next->next == NULL) {
p->next = NULL;
return;
}
deleteLast(p->next);
}
一些更正:
head
list1->head
deleteLast
的返回类型应为void
NULL
之前的两个节点。请记住,这是一个单独的列表,如果您在NULL
之前的某个节点停止,那么如何将前一个节点的指针设置为不指向当前节点?此列表只有一个方向,一旦向前移动,就无法返回O(n)
时间复杂度答案 1 :(得分:0)
假设您要从deletelast
返回已放弃的项目(从列表中取消列出的项目)。
试试这个:
IntSLLNode *IntSLList::deletelast(IntSLLNode *p)
{
IntSLLNode *pNextNext = p->next->next;
if(pNextNext == NULL)
{
// Next element is the last element, because
// the element after that does not exist (pNextNext)
p->next = NULL; // make this element the last element
return pNextNext; // we are returning the abandoned element
// so caller can make memory de-allocations
// or whatever with the abandoned last element
}
else
{
p->next = deletelast(p->next);
}
}
你可以像这样调用递归函数:
IntSLList *pList;
// populate pList
IntSLLNode *abandonedNode = IntSLList::deletelast(pList->head);
// now you can do whatever you want with abandonedNode. Also, the
// variable pList still points to the list, now reduced by one element.