码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode - Reverse Linked List

时间:2015-05-06 06:55:41      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:

Reverse Linked List

2015.5.6 05:04

Reverse a singly linked list.

Solution:

  Too old.

Accepted code:

 1 // 1CE, 1AC, not perfect
 2 /**
 3  * Definition for singly-linked list.
 4  * struct ListNode {
 5  *     int val;
 6  *     ListNode *next;
 7  *     ListNode(int x) : val(x), next(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     ListNode* reverseList(ListNode* head) {
13         if (head == NULL) {
14             return NULL;
15         }
16         
17         ListNode *p1 = head;
18         ListNode *p2 = p1->next;
19         p1->next = NULL;
20         ListNode *p3;
21         while (p2 != NULL) {
22             p3 = p2->next;
23             p2->next = p1;
24             p1 = p2;
25             p2 = p3;
26         }
27         return p1;
28     }
29 };

 

LeetCode - Reverse Linked List

标签:

原文地址:http://www.cnblogs.com/zhuli19901106/p/4480805.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!