单链表(基本操作)

 

#include <iostream>
#include <malloc.h>
#include <stdlib.h>
#include <cstdio>
using namespace std;
typedef struct linknode{
    int data;
    struct linknode *next;
}nodetype;
 //创建链表
nodetype *create(){
    int d;
    nodetype *h = NULL, *s, *t;
    int i = 1;
    cout << "建立一个单链表:" << endl;
    while(1){
       cout << "输入第" << i << "节点的data域值:";
       cin >> d;
       if(d == 0){
          break;
       }
       if(i == 1){
          h = (nodetype *)malloc(sizeof(nodetype));
          h->data = d;
          h->next = NULL;
          t = h;
       }
       else{
          s = (nodetype *)malloc(sizeof(nodetype));
          s->data = d;
          s->next = NULL;
          t->next = s;
          t = s;
       }
       i++;
    }
    return h;
}
 //输出单链表
void disp(nodetype *h){
    nodetype *p = h;
    cout << "输出一个单链表:" << endl;
    if(p == NULL){
       cout << "空表!" << endl;
    }
    while(p != NULL){
       cout << p->data << " " ;
       p = p->next;
    }
    cout << endl;
 }
 //求单链表元素的个数
 int len(nodetype *h){
    int i = 0;
    nodetype *p = h;
    while(p!=NULL){
       p = p->next; i++;
    }
    return i;
}
nodetype *find(nodetype *h, int i){
    nodetype *p = h;
    int j = 1;
    if(i>len(h) || i<0){
       return NULL;
    }
    else{
       while(p!=NULL && j < i){
          j++; p = p->next;
       }
    }
    return p;
}
 //插入节点
nodetype *ins(nodetype *h, int i, int x){
    nodetype *p, *s;
    s = (nodetype *)malloc(sizeof(nodetype));
    s->data = x;
    s->next = NULL;
    if(i==0){
       s->next = h;
       h = s;
    }
    else{
       p = find(h, i);
       if(p!=NULL){
          s->next = p->next;
          p->next = s;
       }
       else{
          cout << "输入的i值不正确。" << endl;
       }
    }
    return h;
}
 //删除第i个节点
nodetype *del(nodetype *h, int i){
    nodetype *p = h, *s;
    if(i==1){
       h = h->next; free(p);
    }
    else{
       p = find(h, i-1);
       if(p!=NULL && p->next!=NULL){
          s = p->next;
          p->next = s->next;
       }
       else{
          cout << "输入的i值不正确!" << endl;
       }
    }
    return h;
}

int main()
{
    int i, length, temp;
    nodetype *p = NULL;
    p = create();
    disp(p);
    cout << "输入删除第几个节点" << endl;
    scanf("%d", &i);
    p = del(p, i);
    disp(p);
    printf("输出单链表的个数:\n");
    length = len(p);
    printf("%d\n", length);
    cout << "输入插入元素的位置:\n" << endl;
    scanf("%d", &i);
    cout << "输入插入元素的值:\n" << endl;
    scanf("%d", &temp);
    p = ins(p, i, temp);
    disp(p);
    return 0;
}


 

你可能感兴趣的:(struct,null,include)