題目
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]時就超時,想不明白。望大神指正
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态