您的位置:首页 > 其它

leetcode题目 反转链表系列问题

2015-10-04 22:19 513 查看
题目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附近。算法效率应该一样,剩下的只是细节上的优化了。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: