每日一题(1)

输入一个链表,输出该链表中倒数第k个节点

注意点:
需要判断所给的K是否大于链表长度

class Solution {
public:
    ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) {
        if(pListHead==NULL)
            return NULL;
        ListNode *node=pListHead;
        ListNode *cur=pListHead;
        while(--k){
            if(node->next!=NULL)
                node=node->next;
            else
                return NULL;
        }
        while(node->next!=NULL){
            node=node->next;
            cur=cur->next;
        }
        return cur;
    }
};

输入两个单调递增的链表,输出两个链表合成后的链表。当然我们需要合成后的链表满足单调不减规则

注意:先把有头节点确定,在链后面节点。

class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2)
    {
        ListNode *list=NULL;
        ListNode *head=NULL;
        if(pHead1==NULL)
            return pHead2;
        if(pHead2==NULL)
            return pHead1;
        if(pHead1->val<=pHead2->val){
            list=pHead1;
            pHead1=pHead1->next;
        }else{
            list=pHead2;
            pHead2=pHead2->next;
        }
        head=list;
        while(pHead1 && pHead2){
            if(pHead1->val>=pHead2->val){
                head->next=pHead2;
                pHead2=pHead2->next;
            }else{
                head->next=pHead1;
                pHead1=pHead1->next;
            }
            head=head->next;
        }
        if(pHead1)
            head->next=pHead1;
        if(pHead2)
            head->next=pHead2;
        return list;
    }
};

输入一个复杂链表(每个节点中都有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),返回结果为复制后复杂链表的head

注意:节点的random指针可能为空,在对齐next使需要判空
解链时为保持代码适用性,原链表和复制后的链表都需要拆开

class Solution {
public:
    RandomListNode* Clone(RandomListNode* pHead)
    {
        if(pHead==NULL)
            return NULL;
        RandomListNode *head=pHead;
        while(head!=NULL){
            RandomListNode *node=(RandomListNode *)malloc(sizeof(RandomListNode));
            node->label=head->label;

            node->next=head->next;
            head->next=node;

            head=head->next->next;
        }

        head=pHead;
        while(head!=NULL){
            if(head->random!=NULL){
                head->next->random=head->random->next;
            }else
                head->next->random=NULL;
            head=head->next->next;
        }

        head=pHead;
        RandomListNode *newlist=pHead->next;
        while(head!=NULL){
            RandomListNode *copy=head->next;
            RandomListNode *cur=copy->next;
            if(cur){
                copy->next=cur->next;
                head->next=cur;
            }else{
                copy->next=NULL;
                head->next=NULL;
            }
            head=head->next;
        }
        return newlist;
    }
};

猜你喜欢

转载自blog.csdn.net/sifanchao/article/details/81294914