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

 

你可能感兴趣的:(LeetCode)