剑指offer——两个链表的合并

我怕是要丸,链表合并不会写了!!!!!!!!!!!!!

题目:输入两个单调递增的链表,输出两个链表合成后的链表,合成后的链表满足单调递增。

首先递归方法

struct ListNode {
	int val;
	struct ListNode *next;
};
ListNode* ReverseList(ListNode* pHead) 
{
        if(pHead == NULL ) return NULL;
        struct ListNode *first=pHead;
        struct ListNode *last=first;
        while(first && first ->next != NULL )
        {
            struct ListNode *tmp=first->next;
            first->next=last;
            last=first;
            first=tmp;
        }
        first->next=last;
        return first;
}

非递归

typedef struct Node{  
    ElemType element;  
    struct Node *next;  
}Node;  

Node* Merge(Node* pHead1, Node* pHead2)
{
	Node *head=NULL;
	Node *ptr=NULL;
	while(pHead1 && pHead2)
	{
		if(pHead1 ->element >= pHead2->element )
		{
			if(head == NULL )
			{
				head=ptr;//head和ptr都指向头,ptr变head不变
				ptr=pHead2;
			}
			else
			{
				ptr->next=pHead2;//ptr的next指向pHead
				ptr=ptr->next;//此刻ptr指向phead2的位置,将较小的数据拉了进来
			}
			pHead2=pHead2->next;
		}
		else
		{
			if(head== NULL )
			{
				head=ptr;
				ptr=pHead1;
			}
			else
			{
				ptr->next=pHead1;
				ptr=ptr->next;
			}
			pHead1=pHead1->next;
		}
	}
	if(pHead1==NULL )
	{
		ptr->next=pHead2;
	}
	else
		ptr->next=pHead1;
	return head;
}

我可能真的药丸,一个非递归调了好久好久,罪过,罪过。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值