Reversal and Merge of Singly Linked List in C Language

Reversal and Merge of Singly Linked List in C Language

Reversal of singly linked list

//定义一个链表结点
struct ListNode{
    
    
	int data;
	ListNode* next;
};

(1) Head node insertion method

void Reversal(LinkNode* head){
    
    
	LinkNode *p,*q;
	p=head->next;
	head->next=NULL;
	while(p){
    
    
		q=p->next;
		p->next=head->next;
		head->next=p;
		p=q;
	}
}

(2) Three-pointer method (in-place reversal method)

void Reversal(struct ListNode* head){
    
    
	LinkNode *pre,*cur,*next;//cur为当前操作结点,pre为上一个结点,next是下一个结点
	pre->next=NULL;
	cur=head->next;
	while(cur){
    
    
		next=cur->next;
		cur->next=pre;
		pre=cur;
		cur=next;
	}
	head->next=pre;
}

(3) Recursive method

void Reversal(struct ListNode* head){
    
    
	//终止条件:找到最后一个节点
	if(head==NULL||head->next==NULL){
    
    
		return head;
	}else{
    
    
		ListNode* newhead=Reversal(head->next);//从最后两个开始反转 
		head->next->next=head;
		head->next=NULL;
		return newhead;
	}
}

Singly Linked List Merge

(1) Iterative method

struct ListNode* mergeTwoLists(struct ListNode* head1, struct ListNode* head2){
    
    
	LinkNode *head3;
	LinkNode *p,*q,*r;
	p=head1->next;
	q=head2->next;
	r=head3=head1;
	while(p&&q){
    
    
		if(p->data<=q->data){
    
    
			r->next=p;
			r=p;
			p=p->next;
		}else{
    
    
			r->next=q;
			r=q;
			q=q->next;
		}
	} 
	if(p) r->next=p;
	if(q) r->next=q;
	free(head2);
	return head3;
} 

(2) Recursive method

struct ListNode* mergeTwoLists(struct ListNode* head1, struct ListNode* head2){
    
    
    if(!head1) return head2;
    if(!head2) return head1;
    if (head1->data < head2->data) {
    
    
        head1->next = mergeTwoLists(head1->next, head2);
        return head1;
    } else {
    
    
        head2->next = mergeTwoLists(head1, head2->next);
        return head2;
    }
}

Guess you like

Origin blog.csdn.net/The_onion/article/details/121412039