【12_206】Reverse Linked List

本来没想出来,刚才突然想到,可以用“头插法”来反转

 

Reverse Linked List

My Submissions
Total Accepted: 66556 Total Submissions: 182891 Difficulty: Easy

 

Reverse a singly linked list.

click to show more hints.

 

Discuss中的递归解法:

 1 public ListNode reverseList(ListNode head) {
 2     return reverseListInt(head, null);
 3 }
 4 
 5 public ListNode reverseListInt(ListNode head, ListNode newHead) {
 6     if(head == null)
 7         return newHead;
 8     ListNode next = head.next;
 9     head.next = newHead;
10     return reverseListInt(next, head);
11 }

 

我的代码:用的是迭代(即循环)的方法

C语言:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* reverseList(struct ListNode* head) {
 9     if (head == NULL || head->next == NULL)
10         return head;
11     struct ListNode* p = head->next;
12     struct ListNode* q = p;
13     head->next = NULL;
14     while(p)    {
15         p = p->next;
16         q->next = head;
17         head = q;
18         q = p;
19     }
20     
21     return head;
22 }

 

posted on 2015-12-16 16:15  Oliver-cs  阅读(206)  评论(0编辑  收藏  举报

导航