链表的相关算法及应用(一)

1.逆置链表(递归、迭代两种方法)

2.逐对逆置链表(递归、迭代)

// 逆置链表	迭代 
LNode *reverse(LinkList &L){
	LNode *pre=NULL;
	LNode *cur=L->next;
	LNode *t;
	while(cur){
		t=cur->next;
		cur->next=pre;
		pre=cur;
		cur=t;
	}
	LNode *newHead = (LNode*)malloc(sizeof(LNode));	//创建新的头结点 
	newHead->next=pre;
	return newHead;		//返回新的头结点 
} 
//逆置链表 递归 
LNode *reverse2(LNode *node,LNode *next){
	if(next){
		LNode *head = reverse2(node->next,next->next);
		next->next=node;	
		node->next=NULL;
		return head;
	}else{
		return node;
	}
} 
LNode* reverse2(LinkList &L){
	if(L==NULL||L->next==NULL)
		return L;
	else{
		LNode *head = (LNode*)malloc(sizeof(LNode));
		head->next=reverse2(L->next,L->next->next);
		return head;
	}
}

 

//逐对逆置链表 迭代 
LNode *reversePair(LNode* head){
	LNode *t1=NULL;
	LNode *t2=NULL;
	while(head&&head->next){
		if(t1){
			t1->next->next=head->next;
		}
		t1=head->next;	
		head->next=head->next->next;
		t1->next=head;
		if(t2==NULL){
			t2=t1;
		//	printf("给头结点赋值 %d\n",t2->data);	
		}
		head=head->next;
	}
	LNode *newHead = (LNode*)malloc(sizeof(LNode));	//创建新的头结点 
	newHead->next=t2;
	print(newHead);
	return newHead;		//返回新的头结点 	
}

 

//逐对逆置链表 递归 
LNode *reversePair2(LNode* head){
	if(head==NULL||head->next==NULL)
		return head;
	else{
		LNode *t=head->next;
		head->next=t->next;
		t->next=head;
		head=t;
		head->next->next=reversePair2(head->next->next);
		return head;
	} 
} 

int main(){
	LinkList L;
	int n=0;
	printf("输入链表长度\n");
	scanf("%d",&n);
	createList(L,n);
	print(L);
	LNode *h = (LNode*)malloc(sizeof(LNode));
	h->next = reversePair2(L->next);
	print(h);
	return 0;
}

  

 

 

猜你喜欢

转载自www.cnblogs.com/hekuiFlye/p/9191559.html