【自我练习】链表的练习题

一、反转链表

【自我练习】链表的练习题_第1张图片

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead == NULL)
            return NULL;
        ListNode *pCur = pHead;
        ListNode *pPrev = NULL; 
        ListNode *pNew = NULL;
        while(pCur != NULL)//当前结点下一个不能空
        {
            ListNode *pNext = pCur->next;
            if(pNext == NULL)
                pNew = pCur;
            //链表反指
            pCur->next = pPrev;
            pPrev = pCur;
            pCur = pNext;
        }
        return pNew;
    }
};

 

二、合并两个单调递增的链表

【自我练习】链表的练习题_第2张图片

【自我练习】链表的练习题_第3张图片

递归:
ListNode *Merge(ListNode *P1, ListNode *P2)
{
	if(P1 == NULL)  return P2;
	if(P2 == NULL)  return P1;
	ListNode *PNew = NULL;
	
	if(P1->val < P2->val)
	{
		PNew = P1;
		P1->next = Merge(P1->next, P2);
	}
	else
	{
		PNew = P2;
		P2->next = Merge(P2->next, P1);
	}
	return PNew;
}

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    //非递归
 
ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
  
        ListNode *p1,*p2,*pre1;
        pre1 = p1 = pHead1; p2 = pHead2;
        while(p1 && p2)
        {
            if(p1->val > p2->val)
            {
                pre1->next = p2;
                p2 = p2->next;
                pre1->next->next = p1;
                pre1 = pre1->next;
            }
            else
            {
                pre1 = p1;
                p1 = p1->next;
            }
        }
        if(p2)
            pre1->next = p2;
          
        return pHead1;   
    }
        /*递归
        if(pHead1->val < pHead2->val)//链一做新链表头
        {
            pRes = pHead1;
            pHead1->next = Merge(pHead1->next, pHead2);
        }
        else
        {
            pRes = pHead2;
            pHead2->next = Merge(pHead2->next, pHead1);
        }
        return pRes;
        */
    }
};

 

你可能感兴趣的:(【自我练习】链表的练习题)