#include<stdlib.h> #include<stdio.h> #define OK 1 #define ERROR 0 #define OVERFLOW -1 #define TRUE 1 #define FALSE 0 typedef int ElemType;//Specify the data type in the linked list typedef int Status; typedef struct LNode { ElemType data; struct LNode *next; }LNode, *LinkList; Status GetElem_L(LinkList L, int i, ElemType &e) { //L is the head pointer of the singly linked list with the head node //When the i-th element exists, assign its value to e and return OK, otherwise return ERROR LinkList p;int j; p = L->next; j = 1; //Initialization, p points to the first node, j is the counter while (p&&j < i) //Search backwards until p points to the i-th element or p is empty { p = p->next; ++j; } if (!p || j>i)return ERROR; //The i-th element does not exist e = p->data; //take the i-th element return OK; } Status ListInsert_L(LinkList &L, int i, ElemType e) { //Insert element e before the i-th position in the singly linked list L with the head node LinkList p, s; int j; p = L;j = 0; while (p&&j < i - 1) //find the i-1th node { p = p->next; ++j; } if (!p || j>i - 1)return ERROR; //i is less than 1 or greater than table length+1 s = (LinkList)malloc(sizeof(LNode)); //Generate a new node s->data = e; s->next = p->next; //insert into LL p->next = s; return OK; } Status ListDelete_L(LinkList &L, int i, ElemType &e) { //In the singly linked list L with the head node, delete the i-th element and return its value by e LinkList p, q; int j; p = L; j = 0; while (p->next&&j < i - 1) //find the i-th node and make p point to its predecessor { p = p->next; ++j; } if (!(p->next) || j>i - 1)return ERROR; //The delete position is unreasonable q = p->next; p->next = q->next; // delete and release the node e = q->data; free(q); return OK; } void CreateList_L(LinkList &L, int n) { //Enter the values of n elements in reverse order, and create a singly linked list L with the head node L = (LinkList)malloc(sizeof(LNode)); L->next = NULL; //Create a singly linked list with a head node first int i; LinkList p; for ( i = n; i > 0; --i) { p = (LinkList)malloc(sizeof(LNode)); //Generate a new node scanf("%d", &p->data); //input element value p->next = L->next; L->next = p; //Insert into header } } void Display(LinkList &L) { LinkList p; p = L->next; while (p) //find the i-th node and let p point to its predecessor { printf("%d ", p->data); p = p->next; } printf("\n"); } intmain() { LinkList L; ElemType e; CreateList_L(L, 5); Display(L); ListDelete_L(L, 2, e); printf("%d", e); Display(L); ListInsert_L(L, 2, e); printf("%d", e); Display(L); return 0; }
Data Structure - linked list ADT (C/C++ language)
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=324850148&siteId=291194637
Recommended
Ranking