zoukankan      html  css  js  c++  java
  • LeetCode 328. 奇偶链表

    题目链接:https://leetcode-cn.com/problems/odd-even-linked-list/

    给定一个单链表,把所有的奇数节点和偶数节点分别排在一起。请注意,这里的奇数节点和偶数节点指的是节点编号的奇偶性,而不是节点的值的奇偶性。

    请尝试使用原地算法完成。你的算法的空间复杂度应为 O(1),时间复杂度应为 O(nodes),nodes 为节点总数。

    示例 1:

    输入: 1->2->3->4->5->NULL
    输出: 1->3->5->2->4->NULL
    示例 2:

    输入: 2->1->3->5->6->4->7->NULL
    输出: 2->3->6->7->1->5->4->NULL
    说明:

    应当保持奇数节点和偶数节点的相对顺序。
    链表的第一个节点视为奇数节点,第二个节点视为偶数节点,以此类推。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     struct ListNode *next;
     6  * };
     7  */
     8 struct ListNode* oddEvenList(struct ListNode* head){
     9     if(head==NULL||head->next==NULL) return head;
    10     struct ListNode *p=head;
    11     struct ListNode *h=head->next;
    12     struct ListNode *q=h;
    13     while(p->next!=NULL&&q->next!=NULL){
    14         p->next=q->next;
    15         p=p->next;
    16         q->next=p->next;
    17         q=q->next;
    18     }
    19     p->next=h;
    20     return head;
    21 }
  • 相关阅读:
    verilog RTL编程实践之四
    TB平台搭建之二
    hdu3466 Proud Merchants
    poj2411 Mondriaan's Dream (用1*2的矩形铺)
    zoj3471 Most Powerful
    poj2923 Relocation
    hdu3001 Travelling
    poj3311 Hie with the Pie
    poj1185 炮兵阵地
    poj3254 Corn Fields
  • 原文地址:https://www.cnblogs.com/shixinzei/p/11410373.html
Copyright © 2011-2022 走看看