您的位置:首页 > Web前端 > Node.js

【LeetCode】Swap Nodes in Pairs & Reverse Nodes in k-Group

2014-04-22 19:33 429 查看
链表题是一个难点,需要多写多练习


Swap Nodes in Pairs

 

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 == NULL || head->next == NULL)	return head;
//printList(head,"head");
//至少两个结点
ListNode *p = head, *prep = NULL;
ListNode *q = p->next;
p->next = q->next;
q->next = p;
head = q;
prep = p;
p = p->next;
//printList(head,"head");
while(p != NULL && p->next != NULL)
{
q = p->next;
p->next = q->next;
q->next = p;
prep->next = q;
prep = p;
p = p->next;
//printList(head,"head");
}
return head;
}
};



Reverse Nodes in k-Group

 Total Accepted: 7206 Total
Submissions: 29535My Submissions

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 == NULL || head->next == NULL || k == 1) return head;
int i = 0;
ListNode *tmphead = head, *tmptail = head, *tmpSaveHead = NULL,*tmpSaveTail = NULL , *p;

while(tmptail != NULL)
{
while(++i<k && tmptail != NULL)
tmptail = tmptail->next;
if(tmptail == NULL) return head;
tmpSaveTail = tmptail->next;
//printList(tmphead,"tmphead");
p = tmphead->next;
tmptail = tmphead;
while(i-- > 1)
{
tmptail->next = p->next;
p->next = tmphead;
tmphead = p;
p = tmptail->next;
}

if(tmpSaveHead)	tmpSaveHead->next = tmphead;
else	head = tmphead;
tmpSaveHead = tmptail;
//printList(tmphead,"1tmphead");
//system("pause");
//printList(head,"head");
//system("pause");
tmphead  = tmpSaveTail;
tmptail = tmpSaveTail;
i = 0;
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: