leetcode 518,[leetcode]328. Odd Even Linked List

 2023-10-17 阅读 28 评论 0

摘要:題目 Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes. You should try to do it in place. The program should run in O(1) space complexi

題目

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

leetcode 518、Example:
Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on …

翻譯
將一個單鏈表按節點的奇偶次序排序,奇數節點在前面,偶數節點在后面
思路
定義兩個奇偶鏈表的頭指針,然后遍歷鏈表,奇數節點放在奇數鏈表,偶數節點放在偶數鏈表,最后將偶數鏈表的頭插入奇數鏈表的尾部

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     struct ListNode *next;* };*/
struct ListNode* oddEvenList(struct ListNode* head) {struct ListNode *podd, *peven, *peven_head, *tmp;if(!head || !head->next)return head;podd = head;peven_head = peven = head->next;tmp = head->next->next;while(NULL != tmp){podd->next = podd = tmp;if(NULL == tmp->next){break;}peven->next = peven = tmp->next;tmp = tmp->next->next;}podd->next = peven_head;return head;
}

試了幾個測試用例都是對的,但時間超過限制,而且測試用例為[1,2,3,4,5,6,7,8]時就超時,想不明白。望大神指正

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/143574.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息