+ -
当前位置:首页 → 问答吧 → C++链表节点删除问题

C++链表节点删除问题

时间:2011-12-18

来源:互联网

如下:
C/C++ code


#include<iostream>
using namespace std;

struct book
{
    int num;
    float price;
    book *next;
};

book *head = NULL;
book *creat()
{
    book *p1, *p2;
    p1 = new book;


    cout <<"请输入图书编号,以0结束:";
    cin >> p1->num;
    if(p1->num != 0)
    {
        head = p1;
        p2 = p1;
        cout << "请输入图书价格:" ;
        cin >> p1->price;
    }
    else
    {
        delete p1;
        //p2->next = NULL;
        return head;
    }
    while(p1->num != 0)
    {
        p2 = p1;
        p1 = new book;
        cout <<"请输入图书编号,以0结束:";
        cin >> p1->num;
        if(p1->num != 0)
        {
            cout << "请输入图书价格:" ;
            cin >> p1->price;
        }
        p2->next = p1;
    }
    delete p1;
    p2->next = NULL;
    return head;
}

void print(book *head)
{
    cout << endl;
    while(head)
    {
        cout << "图书编号为:" << head->num <<"\t";
        cout << "图书价格为:" << head->price << "\t";
        head = head->next;
        cout << endl;
    }
}

void delete1(book *head, int num)
{
    book *l;
    if(head->num == num)   //输入的编号为第一个节点时
    {
        l = head;
        ::head = head->next;
        delete l;
        cout << "操作成功"<< endl;
        return;
    }
    while(head)
    {
        if(head ->next == NULL)
        {
            cout << "找不到输入的编号节点" << endl;
            return;
        }

        if(head->next->num == num)
        {
            l = head->next;
            head->next = l->next;
            delete l;
            cout << "操作成功" << endl;
            return;
        }
        head = head->next;

    }
    cout << "找不到输入的编号节点" << endl;
}
int main()
{
    book *a;
    a = creat();
    print(a);
    cout << "请输入要删除的节点图书编号:" << endl;
    int booknum;
    cin >> booknum;
    delete1(a, booknum);
    print(a);
    return 0;
}




当我删除第一个节点的时候,后面的节点不会往上移;
各位大吓帮忙看看,小弟先谢了~~~

作者: rere02   发布时间: 2011-12-18

顺序表,当你删除一个元素时,其实并没删除那快内存,而是后面的元素依次前移,当前长度减一,而链表是删除结点,头指针指向删除后的那个结点。删除第一个结点:p=first;first = first->link;delete p,

作者: jackhanzy   发布时间: 2011-12-18