单向链表的建立,插入,删除(复习一下)

#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
typedef int datetype;
typedef struct  node
{
    datetype date;
    struct node* next;
}listnode,*linklist;
linklist creatlist(int num)//创建链表
{
    int i;
    linklist tail=NULL,temp=NULL,head=NULL;
    for(i=0;i<num;i++)
    {
        if(head==NULL)
        {
            head=(listnode*)malloc(sizeof(listnode));
            head->next=NULL;
            cin>>head->date;
            tail=head;
        }
        else
        {
            temp=(listnode*)malloc(sizeof(listnode));
            cin>>temp->date;
            tail->next=temp;
            tail=temp;
            tail->next=NULL;
        }
    }
    return head;
}
linklist insert(linklist head,int i,int num)
{
    int j=0;
    linklist p=head,temp=NULL,node=NULL;
    temp=(linklist)malloc(sizeof(listnode));
    if(i==0)
    {
        temp->date=num;
        temp->next=head;
        return temp;
    }
    for(j=0;j<i;j++)
    {
        node=p;            //找到前驱指针和后继指针
        p=p->next;
    }
    temp->date=num;
    node->next=temp;
    temp->next=p;
    return head;
}
linklist deletelist(linklist head,int i)
{
    int j=1;
    linklist p=head,temp,node;//找到前驱指针和后继指针
    if(i==1)
    {
        head=head->next;
        return head;    
    }
    for(j=1;j!=i;j++)
    {
        node=p;
        p=p->next;
    }
    node->next=p->next;
    return head;
}
void outputlist(linklist head)
{
    linklist p=head;
    while(p!=NULL)
    { 
        cout<<p->date<<' ';
        p=p->next;
    }
}
int main()
{
    linklist head;
    int num,i;
    cin>>num;
    head=creatlist(num);
    outputlist(head);
    cin>>i>>num;
    head=insert(head,i,num);
    outputlist(head);
    cin>>i;
    deletelist(head,i);
    outputlist(head);    
}
原文地址:https://www.cnblogs.com/a1225234/p/4612679.html