Linked list operation of linear list
1. Structure definition
typedef struct LNode* LinkedList;
typedef struct LNode
{
ElemType data;
struct LNode* next;
}LNode;
2. Linked list initialization
bool InitLinkedList(LinkedList &L)
{
L = (LinkedList)malloc(sizeof(struct LNode));
if(!L) exit(OVERFLOW);
L->next = NULL;
return success;
}
3. Insert an element at the specified position in the linked list
bool LinkedListInsert(LinkedList &L, int index, ElemType e)
{
LNode* p = L; int i = 1;
while(p && i < index)
{
p = p->next;
i++;
}
if(!p || i > index) return failed;
LNode* s = (LNode* )malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return success;
}
4. Delete the element at the specified position of the linked list
bool LinkedListDelete(LinkedList &L, int index)
{
LNode* p = L; int i = 1;
while(p->next && i < index)
{
p = p->next;
i++;
}
if(!p->next || i > index) return failed;
LNode* s = p->next;
p->next = s->next;
free(s);
return success;
}
5. Get the specified position element
bool GetLinkedListElem(LinkedList L, int index, ElemType &e)
{
LNode* p = L->next; int i = 1;
while(p && i < index)
{
p = p->next;
i++;
}
if(!p || i > index)return failed;
e = p->data;
return success;
}
6. Get the position of the specified element in the linked list
int LocateLinkedListElem(LinkedList L, ElemType e)
{
LNode* p = L->next; int i = 1;
while(p && p->data != e)
{
p = p->next;
i++;
}
if(p)return i;
return -1;
}
7. Traverse the linked list from beginning to end
void ReadLinkedList(LinkedList &L)
{
LNode* p = L->next;
while(p)
{
printf("%d\n",p->data);
p = p->next;
}
}