zoukankan      html  css  js  c++  java
  • 链表的相关算法及应用(一)

    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
    ",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("输入链表长度
    ");
    	scanf("%d",&n);
    	createList(L,n);
    	print(L);
    	LNode *h = (LNode*)malloc(sizeof(LNode));
    	h->next = reversePair2(L->next);
    	print(h);
    	return 0;
    }
    

      

     

     

  • 相关阅读:
    Java面试知识点总结
    Log4j常用配置及使用
    Eclipse+tomcat+axis2进行web service部署
    iframe内点击a标签禁止滚动到顶部
    VScode首选项
    Bookmarks
    VScode常用插件
    slideout
    bs-loading
    iPhone X 上删除白条
  • 原文地址:https://www.cnblogs.com/hekuiFlye/p/9191559.html
Copyright © 2011-2022 走看看