206.反转链表

力扣

题意:反转一个单链表。

示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

思路

使用双指针法做。注意使用双指针法的时候,不要改变元素的位置,可以添加额外的指针来凑双指针。若改变元素位置来做,容易陷入死循环,导致做错。

C语言代码如下:

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;
* };
*/
/* pre cur cur->next */
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* cur;
struct ListNode* temp;
struct ListNode* pre =NULL;
cur = head;
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur =temp;
}

return pre;
}