1 /**
2 * Definition of ListNode
3 *
4 * class ListNode {
5 * public:
6 * int val;
7 * ListNode *next;
8 *
9 * ListNode(int val) {
10 * this->val = val;
11 * this->next = NULL;
12 * }
13 * }
14 */
15 class Solution {
16 public:
17 /**
18 * @param head: The first node of linked list.
19 * @return: The new head of reversed linked list.
20 */
21 ListNode *reverse(ListNode *head) {
22 // write your code here
23 ListNode *l1=NULL,*l2=NULL,*l3=NULL;
24
25 l1 = head;
26 // 链表没有节点或有一个节点
27 if(l1 == NULL || l1->next == NULL) {
28 return l1;
29 }
30 l2 = l1->next;
31 // 链表有2节点
32 if(l2->next == NULL) {
33 l2->next = l1;
34 l1->next = NULL;
35 return l2;
36 }
37 l3 = l2->next;
38 // 链表有3个以上节点
39 if(l2->next != NULL) {
40 while(l2 != l3) {
41 l2->next = l1;
42 if(l1 == head)
43 l1->next = NULL;
44 l1 = l2;
45 l2 = l3;
46
47 if(l3->next != NULL)
48 l3 = l3->next;
49 }
50 l2->next = l1;
51 return l2;
52 }
53 }
54 };
55