带头结点的单链表C++

// ConsoleApplication9.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include"iostream"
using namespace std;

typedef int data;
typedef struct link_node
{
    data info;
    link_node *next;
}node;

node *init()
{
    node *head = (node*)malloc(sizeof(node));
    head->next = NULL;
    return head;
}

node *insert_head(node *head, data x)
{
    node *p = head;
    node *q = (node*)malloc(sizeof(node));
    q->info = x;
    q->next = p->next;
    head->next = q;
    return head;
}


int print(node *head)
{
    node *p = head;
    if (p->next == NULL)
        cout << "It is empty!" << endl;
    else
    {
        while (p->next!=NULL)
        {
            cout << p->next->info << endl;
            p = p->next;
        }
    }
    return 0;
}



node *del_x(node *head, data x)
{
    node *p = head;
    while (p->next->info != x)
        p = p->next;
    p->next = p->next->next;
    return head;
}

node *insert(node *head, data x, data n)
{
    node *p = head;
    node *q = (node*)malloc(sizeof(node));
    q->info = n;
    q->next = NULL;

    while (p->next!=NULL && p->info != x)
        p = p->next;
    q->next=p->next;
    p->next = q;

    return head;
}

int _tmain(int argc, _TCHAR* argv[])
{

    node *head = init();
    for (int i = 0; i < 5;i++)
        head=insert_head(head, 999+i);
    print(head);

    cout << "*********" << endl;

    head=del_x(head, 1002);
    print(head);

    cout << "**********" << endl;

    head = insert(head, 1001, 9999);
    print(head);

    return 0;
}
posted @ 2019-12-21 21:54  Butcher512  阅读(273)  评论(0)    收藏  举报