Data structure exercises-singly linked list (1)

first question

There is a singly linked list L with a leading node, and an algorithm is designed to make its elements increase in order

Ideas

First copy the data of the linked list to the array, and then use any one of the eight sorts in the array to sort, and then use the tail interpolation method to insert into the linked list

Void sort(LinkList &L){
    
    
	LNode *p=L->next,*pre;
	LNode *r=p->next,*
	p->next = NULL;
	p=r;
	while(pre->next!=NULL&&pre->next->data<p->data){
    
    
		pre=pre->next;
		p->next = pre->next;
		pre->next = p;
		p=r;
	}
}

Second question

Try to write an efficient algorithm for deleting a minimum node from the singly linked list L with the algorithm taking the lead.

Ideas

Double pointers, one is used to traverse the linked list, and the other is used to record the position of the minimum value in the currently traversed data. When the traversal ends, it can be deleted directly at the position where the minimum value is recorded.

LinkList Delect_Min(LinkList &L){
    
    
	LNode *pre=L, *p=pre->next;
	LNode *minpre=pre,*minp=p;
	while(p!=NULL){
    
    
		if(p->data<minp->data){
    
    
			minp=p;
			minpre=pre;
		}
		pre=p;
		p=p->next;
	}
	minpre->next = min->next;
	free(minp);
	return L;
}

Third question

Two integer sequences A, B, determine whether B is a subsequence of A

Ideas

When traversing A, compare whether there is the same number as the first number of B. If it is not at the end of the traversal, it means that it is not. If it exists, traverse A and B synchronously and compare the sizes, and then the tails of the traversed B are equal It is only then that B is a subsequence of A

int patten(LinkList A,LinkList B){
    
    
	LNode *p=A;
	LNode *pre=p;
	LNode *q=B;
	while(p&&q)
		if(p->data==q->data){
    
    
			p=p->next;
			q=q->next;
		}
		else{
    
    
			pre=pre->next;
			p=pre;
			q=B;
		}
		if(q==NULL)
			return 1;
		else
			return 0;
}

Guess you like

Origin blog.csdn.net/qq_41606378/article/details/108963452