c*******r 发帖数: 309 | 1 问了一个链表,1->2->3->4->5, 每两个交换,2->1->4->3->5,如果单数
情况返回最后一个。要求recursive和iterative两种方法
这个如何recursive? |
P**l 发帖数: 3722 | 2 不到两个就停下来
够了的话,每次处理完两个,函数call第三个node就行了吧 |
l*****a 发帖数: 14598 | 3 void Swap2Nodes(element ** head)
{
current=*head;
if(current==null||current->next==null) return;
element *next,*nextnext;
next=current->next;
nextnext=next->next;
Swap2Nodes(&nextnext);
*head=next;
next->next=current;
current->next=nextnext;
return;
}
【在 c*******r 的大作中提到】 : 问了一个链表,1->2->3->4->5, 每两个交换,2->1->4->3->5,如果单数 : 情况返回最后一个。要求recursive和iterative两种方法 : 这个如何recursive?
|
Y**B 发帖数: 144 | |
q****x 发帖数: 7404 | 5 i prefer:
Node* swap2nodes(Node* head);
【在 l*****a 的大作中提到】 : void Swap2Nodes(element ** head) : { : current=*head; : if(current==null||current->next==null) return; : element *next,*nextnext; : next=current->next; : nextnext=next->next; : Swap2Nodes(&nextnext); : *head=next; : next->next=current;
|
q****x 发帖数: 7404 | 6 node.
【在 Y**B 的大作中提到】 : 是只换数据还是换node的顺序?
|
l*****a 发帖数: 14598 | 7 that is fine
then u need two node*
【在 q****x 的大作中提到】 : i prefer: : Node* swap2nodes(Node* head);
|
q****x 发帖数: 7404 | 8 one ah. 7 line is enough.
Node* swap2(Node* head)
{
if ( head != NULL && head->next != NULL ) {
Node* t = head->next;
head->next = swap2(t->next);
t->next = head;
head = t;
}
return head;
}
【在 l*****a 的大作中提到】 : that is fine : then u need two node*
|
|
w****x 发帖数: 2483 | 9 NODE* SwapNodes(NODE* pHead)
{
assert(NULL != pHead);
if (pHead->pNext == NULL)
return pHead;
NODE* pRet = pHead->pNext;
NODE* pIter = pHead;
NODE* pPrev = NULL;
while (pIter != NULL && pIter->pNext != NULL)
{
if (NULL != pPrev)
pPrev->pNext = pIter->pNext;
NODE* pTmp = pIter->pNext->pNext;
pIter->pNext->pNext = pIter;
pIter->pNext = pTmp;
pPrev = pIter;
pIter = pIter->pNext;
}
return pRet;
} |
s*******f 发帖数: 1114 | 10 Node* SwapNeibor(Node *head){
if (!head || !head->next)
return head;
Node *p = head->next;
Node *q = p->next;
p->next = head;
head->next = SwapNeibor(q);
return p;
}
【在 c*******r 的大作中提到】 : 问了一个链表,1->2->3->4->5, 每两个交换,2->1->4->3->5,如果单数 : 情况返回最后一个。要求recursive和iterative两种方法 : 这个如何recursive?
|