leetcode【链表】-----206. Reverse Linked List(反转链表)
1、题目

2、分析
链表的题目一般都是需要用一个虚拟的节点来作为中间节点,不停改变指针的值。使用一个cur指针记录当前节点,pre记录前驱节点,temp作为中间变量,其中cur可以直接用head代替。之后通过迭代完成操作。
3、代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//if(head=NULL) return NULL;
ListNode* pre=NULL;
ListNode* cur=head;
while(cur!=NULL){
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;
cur=temp;
}
return pre;
}
};
4、相关知识点
链表的指针变换。

浙公网安备 33010602011771号