zoukankan      html  css  js  c++  java
  • Leetcode 328 Odd Even Linked List 链表

    Given 1->2->3->4->5->NULL,
    return 1->3->5->2->4->NULL.

    就是将序号为单数的放在前面,而序号为偶数的放在后面

    我的方法是讲序号为偶数的的插入到链表末尾

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* oddEvenList(ListNode* head) {
    12         if(!head) return head;//空链表返回
    13         ListNode* last = head;
    14         int cnt = 1;
    15         for(; last->next; last = last->next, ++cnt);
    16         if(cnt < 3) return head;//链表长度小于3返回
    17         ListNode* now = head;
    18         ListNode* end = last;
    19             
    20         for(int i = 0; i< cnt/2; now = now->next, ++i){
    21             
    22             ListNode* next = now->next;
    23             now->next = next->next;
    24                 
    25             end->next = next;
    26             next->next = NULL;
    27                 
    28             end = next;
    29             
    30         }
    31         return head;
    32     }
    33 };
  • 相关阅读:
    AWR报告生成
    ios-html-get/post差额,简而言之(MS)CheckST
    2015第33周一
    2015第32周日
    2015第32周六
    2015第32周五
    2015第32周四
    2015第32周三
    2015第32周二
    2015第32周一
  • 原文地址:https://www.cnblogs.com/onlyac/p/5212048.html
Copyright © 2011-2022 走看看