leetcode题目 反转链表系列问题

题目1: Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.
思路: 这种问题采用递归和非递归都可以解决,但是非递归考虑的情况比较多,比如说链表为空,链表只有一个节点,链表有偶数个节点,链表有奇数个节点。也曾写过循环实现,但是代码太长。相反递归就简洁明了的多。

class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(!head||!head->next)
            return head;
        ListNode* p1,*p2;
        p1=head;
        head=head->next;
        p2=head->next;
        head->next=p1;
        p1->next= swapPairs(p2) ;
        return head;
    }
};

运行时间小于1ms,还击败了99%的代码。
这里写图片描述

题目2: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5

思路: 有了前边题的预热,这题也比较简单了,仍然递归实现。同时调用了翻转单个链表的函数。

 class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(!head)
            return NULL;

        ListNode* p1=head,*p2=head,*p3=head;
        for(int i=1;i<k&&p1!=NULL;++i)
            p1=p1->next;
        if(!p1)
            return head;
        p2=p1->next;
        p1->next=NULL;
        reverseSingle(&head,head);
        p3->next=reverseKGroup(p2, k); 
        return head;
    }
    void reverseSingle(ListNode** head,ListNode* p)
    {
        if(!p->next)
        {
            *head=p;
            return;
        }
        reverseSingle(head,p->next);
        p->next->next=p;
        p->next=NULL;
    }
};

运行通过,但是只击败了49%的代码,但是看大家的时间都集中在24ms附近。算法效率应该一样,剩下的只是细节上的优化了。
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值