Leetcode 328. 奇偶链表(将节点编号为奇数和偶数的链表分别排在一起)

tech2023-01-14  120

我写的代码

class Solution { public: ListNode* oddEvenList(ListNode* head) { if(head==NULL) return head; ListNode* evenHead = new ListNode(-1); ListNode* evenTail = evenHead; ListNode* p = head; while(p&&p->next){ ListNode* q = p->next; evenTail->next = q; evenTail = evenTail->next; p->next = q->next; q->next = NULL; if(p->next!=NULL) p = p->next; else break; } p->next = evenHead->next; return head; } };

标准答案代码: 奇偶指针解耦移动,很漂亮。

class Solution { public: ListNode* oddEvenList(ListNode* head) { if (head == NULL) return NULL; ListNode* odd = head, *even = head->next, *evenHead = even; while (even != NULL && even->next != NULL) { odd->next = even->next; odd = odd->next; even->next = odd->next; even = even->next; } odd->next = evenHead; return head; } };

 

最新回复(0)