Data Structure (Algorithms) - Linear Table 2 (Single Linked List)

Keywords: Programming



/**
Singly Linked List
Double linked list

1,Empty linear table setNull(L)
2,insert Adding elements
3,Find elements by location
4,Find all elements
5,Delete an element	
*/

#include <iostream>

using namespace std;

typedef char ElemType;

//Singly Linked List
struct LNode{
	ElemType data;
	struct LNode *next;
};


void setNull(struct LNode **p){
	*p=NULL;
}


void insert(struct LNode **p , ElemType x , int i){
	int j=1;
	struct LNode *s , *q;
	s=(struct LNode *)malloc(sizeof(struct LNode));
	s->data=x;
	q=*p;
	if(i == 1){//Front insertion head node
		s->next=q;
		*p=s;
	}else{
		while(j<i-1 && q->next != NULL){//Intermediate insertion to locate elements
			q=q->next;
			j++;
		}
		if(j == i-1){       //Locate to the appropriate location
			s->next=q->next;//The next node of ** s points to the next node of q
			q->next=s;		//The next node of q points to s to form a linked list

		}else{
			cout<<"Wrong location"<<endl;
		}
	}
		
}

void display(struct LNode **p ){
	struct LNode *q;
	q=*p;
	cout<<"Single linked list:"<<endl;
	if(q== NULL){
		cout<<"Linked list is empty."<<endl;
	}else if(q->next == NULL){
		printf("%c",q->data);
	}else{
		while(q->next != NULL){
			printf("%c->",q->data);
			q=q->next;
		}
		printf("%c",q->data);
	}
	printf("\n");
}

void del(struct LNode **p,int i){
	int j=1;
	struct LNode *q=*p,*t;
	
	if(i == 1){//Delete header nodes
		t=q;
		*p=q->next;//Cover the previous node directly with the latter node
	}else{
		while(j<i-1 && q->next != NULL){//Find the location of deleted elements
			q=q->next;
			j++;
		}
		if(j == i-1 && q->next != NULL){//Locate to the appropriate location
			t=q->next;//Once located, assign a value to the node to be deleted
			q->next=t->next;//T - > next assignment to Q - > next overrides (deletes)
		}else{
			cout<<"Wrong location"<<endl;
		}
		if(t != NULL){
			free(t);//Final destruction	
		}
	}
}


void main(){
	struct LNode *head;
	setNull(&head);
	insert(&head,'a',1);
	insert(&head,'b',2);
	insert(&head,'a',2);
	insert(&head,'c',4);
	insert(&head,'d',3);
	insert(&head,'e',1);//Forward interpolation

	display(&head);
	
	
	del(&head,1);//Delete node
	display(&head);

	del(&head,5);//Censored node
	display(&head);

	del(&head,3);//Delete the intermediate node
	display(&head);

}




 

test result

Single linked list:
e->a->a->d->b->c
Single linked list:
a->a->d->b->c
Single linked list:
a->a->d->b
Single linked list:
a->a->b

Posted by lucianbeauty on Sun, 03 Feb 2019 01:12:15 -0800