LeetCode 206: Reverse Linked List

Reverse a singly linked list.Hint: A linked list can be reversed either iteratively or recursively. Could you implement both?

题意

翻转该单链表

思路

使用迭代法或者递归法皆可实现。

代码

C语言版本:
iteratively(迭代方法)

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

分享到 评论