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 };
  • 相关阅读:
    DAY21
    DAY20
    DAY19
    @Autowired注解和静态方法
    PageHelper.startPage和new PageInfo(list)的一些探索和思考
    escape()、encodeURI()、encodeURIComponent()区别详解
    每日日报29
    1dialog 表单最基本的封装
    mongoose
    数组
  • 原文地址:https://www.cnblogs.com/onlyac/p/5212048.html
Copyright © 2011-2022 走看看