题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param pHead ListNode类
* @return ListNode类
*/
struct ListNode* ReverseList(struct ListNode* pHead ) {
struct ListNode* f1=NULL;
struct ListNode* f2=pHead;
struct ListNode* tmp;
while (f2) {
tmp=f2->next;
f2->next=f1;
f1=f2;
f2=tmp;
}
return f1;
// write code here
}
解题思路
- 主要就是双指针。定义两个指针,前一个指向NULL,后一个指向head
- 把f2->next用tmp保存,因为接下来会改变这个next的指向
- 将f2->next指向f1
- 继续移动两个指针
- 最后return


