链表可以解决顺序表的缺点 我们今天简单引用下链表 这边是代码讲解
头文件
#pragma once
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<stdlib.h>
using namespace std;
typedef struct student
{union {int data;int len;};struct student* next;
}plist ,*Plist;
Plist create();
int header(Plist, int);
int output(Plist);
int rear_ins(Plist, int);
int Randomly_inserted(Plist, int , int );
int Randomly_dele(Plist, int);
函数文件
#include"linkk1.h"
Plist create()
{Plist L = (plist*)malloc(sizeof(plist));if (L == NULL){cout << "创建失败";cout << endl;return NULL;}L->len = 0;L->next = NULL;return L;}
int header(Plist L, int pos)
{if (L ==NULL){printf("创建失败");return -1;}Plist p = (plist*)malloc(sizeof(plist));p->next = L->next;L->next = p;p->data = pos;L->len++;return 0;}
int output(Plist L)
{Plist t = L;while (t ->next!= NULL){t = t->next;cout <<" " << t->data;}return 0;
}
int rear_ins(Plist L, int pos)
{Plist p = L;while (p->next != NULL){p = p->next;}Plist t = (plist*)malloc(sizeof(plist));p->next = t;t->next = NULL;t->data = pos;return 0;}
int Randomly_inserted(Plist L, int pos, int e) {int i = 0;Plist t = L;for (i = 1; i <=pos; i++){t = t->next;}Plist p = (plist*)malloc(sizeof(plist));p->next = t->next;t->next = p;p->data = e;return 0;}
int Randomly_dele(Plist L, int pos)
{int i = 0;Plist t = L;for (i = 1; i < pos; i++){t = t->next;}Plist q = t->next;t->next = q->next;free(q);q = NULL;return 0;
}
源文件调试
#include"linkk1.h"
int main()
{int a[] = { 10,9,8,23,231232,3121,2324,56,789,22 };Plist L = create();for (int i = 0; i <( sizeof(a) / sizeof(a[0])); i++){header(L, a[i]);}rear_ins(L, 2);Randomly_inserted(L, 3, 15);Randomly_dele(L, 3);output(L);
}