【12_206】Reverse Linked List

时间:2021-01-19 18:51:12

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

Reverse Linked List

My Submissions

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

Reverse a singly linked list.

click to show more hints.

Discuss中的递归解法:

 public ListNode reverseList(ListNode head) {
return reverseListInt(head, null);
} public ListNode reverseListInt(ListNode head, ListNode newHead) {
if(head == null)
return newHead;
ListNode next = head.next;
head.next = newHead;
return reverseListInt(next, head);
}

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

C语言:

 /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL || head->next == NULL)
return head;
struct ListNode* p = head->next;
struct ListNode* q = p;
head->next = NULL;
while(p) {
p = p->next;
q->next = head;
head = q;
q = p;
} return head;
}