zoukankan      html  css  js  c++  java
  • LeetCode: Reverse Linked List II

    没做出来,看网上答案,这题难度在于编程

     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 *reverseBetween(ListNode *head, int m, int n) {
    12         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (!head) return NULL;
    15         ListNode *q = NULL;
    16         ListNode *p = head;
    17         for (int i = 0; i < m-1; i++) {
    18             q = p;
    19             p = p->next;
    20         }
    21         ListNode *end = p;
    22         ListNode *pPre = p;
    23         p = p->next;
    24         for (int i = m+1; i <= n; i++) {
    25             ListNode *pNext = p->next;
    26             p->next = pPre;
    27             pPre = p;
    28             p = pNext;
    29         }
    30         end->next = p;
    31         if (q) q->next = pPre;
    32         else head = pPre;
    33         return head;
    34     }
    35 };

     C#

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     public int val;
     5  *     public ListNode next;
     6  *     public ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public ListNode ReverseBetween(ListNode head, int m, int n) {
    11         if (head == null) return null;
    12         ListNode q = null, p = head;
    13         for (int i = 0; i < m-1; i++) {
    14             q = p;
    15             p = p.next;
    16         }
    17         ListNode end = p, pPre = p;
    18         p = p.next;
    19         for (int i = m+1; i <= n; i++) {
    20             ListNode pNext = p.next;
    21             p.next = pPre;
    22             pPre = p;
    23             p = pNext;
    24         }
    25         end.next = p;
    26         if (q != null) q.next = pPre;
    27         else head = pPre;
    28         return head;
    29     }
    30 }
    View Code
  • 相关阅读:
    细看运维85条军规,是否触动了你内心深处那根弦?
    SQL语句的CRUD
    sqlserver数据库类型对应Java中的数据类型
    Struts2文件上传--多文件上传(插件uploadify)
    web.xml文件详解
    关于Java的散列桶, 以及附上一个案例-重写map集合
    hibernate多表查询封装实体
    spring的7个模块
    Struts标签库详解【3】
    Struts标签库详解【2】
  • 原文地址:https://www.cnblogs.com/yingzhongwen/p/3031946.html
Copyright © 2011-2022 走看看