LeetCode OJ:Reverse Linked List (反转链表)

Reverse a singly linked list.

做II之前应该先来做1的,这个倒是很简单,基本上不用考虑什么,简单的链表反转而已:

 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* reverseList(ListNode* head) {
12         if(head == NULL) return NULL;
13         ListNode * prev = NULL;
14         ListNode * p = head;
15         ListNode * next;
16         while(p != NULL){
17             next = p->next;
18             p->next = prev;
19             prev = p;
20             p = next;
21         }
22         return prev;
23     }
24 };

 java版本的如下所示,基本上没什么区别,就是普通解法:

 1 /**
 2  * Definition for singly-linked list.
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public ListNode reverseList(ListNode head) {
11         if(head == null)return null;
12         ListNode helper = new ListNode(-1);
13         helper.next = head;
14         ListNode p = helper;
15         ListNode pPre = helper.next;
16         ListNode tmp = null;
17         while(p.next!=null){
18             tmp = p.next;
19             p.next = pPre;
20             pPre = p;
21             p = tmp;
22         }
23         p.next = pPre;
24         helper.next.next = null; //记得将尾节点的下一个指向null
25         return p;
26     }
27 }

 

其实翻转链表还可以使用一种递归的方式,代码如下:

 1 ListNode * ReverseListIncur(ListNode * node, ListNode * prev)
 2 {
 3     if (node == NULL)
 4         return NULL;
 5     ListNode * tmp = ReverseListIncur(node->next, node);
 6     node->next = prev;
 7     if (tmp == NULL)
 8         return node;
 9     else
10         return tmp;
11 }

 

posted @ 2015-10-13 13:05  eversliver  阅读(262)  评论(0编辑  收藏  举报