Basic operations of sequential tables in linear tables (create, insert, delete, output) and basic operations of singly linked lists (create, delete, output)

Singly linked list: (using citation, run on c++)
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100//maximum length
typedef struct//create
{ int* i; int length; } sqlist; bool newsqlist(sqlist& L) { Li = (int*)(malloc)(sizeof(int[MAXSIZE]));//Apply for space if (!Li) { return false; } else { L.length = 0; //Be careful not to omit return true; } } bool Insert(sqlist& L, int i, int j)//i is the address, j is the element { if (i<1 || i>L.length + 1) { return false ; )//Address error if (L.length >= MAXSIZE)//Insufficient space return false;
























for (int j = L.length-1; j >= i-1; j–)//Move all elements after the insertion point backward by one unit
{ Li[j + 1] = Li[j]; } Li [i-1] = j;//overwrite the original element L.length++; return true; } bool Get(sqlist L, int i,int &e)//i is the address, j is the element, & represents the reference { if (i<1 || i>L.length + 1) return false; e = Li[i-1];//The address starts from 1, and the subscript starts from zero, so subtract one. return true; } bool deletem(sqlist& L, int i) { if (i<1 || i>L.length + 1) return false; else { for (int j = i; j <L.length; j++) { Li[j-1] = Li [j]; } L.length–; } return true; }



























int locate(sqlist L, int i)
{
for (int j = 0; j < L.length;j++)
{
if (L.i[j] == i)
{
return j + 1;
}
}
return 0;
}
int main()
{
sqlist L;
int l, e, p;
if (!newsqlist(L))
printf(“new sqlist failed\n”);
else
{
printf(“new sqlist ready\n”);
printf(“input the length\n”);
scanf_s("%d", &l);
printf(“input the data:\n”);
for (int i = 1; i <= l; i++)
{
scanf_s("%d", &e);
Insert(L, i, e);
}
printf(“the sqlist is\n”);
for (int i = 1; i <= L.length; i++)
{
Get(L, i, e);
printf("%d", e);
}
printf(“input the location to delete:\n”);
scanf_s("%d", &l);
deletem(L, l);
for (int i = 1; i <= L.length; i++)
{
Get(L, i, e);
printf("%d “, e);
}
printf(”\n input the elem to locate\n");
scanf_s("%d", &e);
p = locate(L, e);
if (!p)
{
printf(“error”);
}
else
{
printf("%d", p);
}
}
return 0;
}
单链表:
#include<stdio.h>
#include<stdlib.h>
struct ListNode {
int data;
struct ListNode* next;``
};
struct ListNode* readlist();
void print(struct ListNode* l);
struct ListNode* deletem(int i, struct ListNode* j);
int main()
{
struct ListNode* l = readlist();
int i;
scanf_s("%d", &i);
l = deletem(i, l);
return 0;
}
struct ListNode* readlist()
{
struct ListNode* head, * tail, * p;
head = NULL;
tail = NULL;
while (1)
{
p = (struct ListNode*)(malloc(sizeof(struct ListNode)));
scanf_s("%d", &p->data);
if (p->data == -1)
break;
p->next = NULL;
}
}

Guess you like

Origin blog.csdn.net/weixin_51235620/article/details/114672849