Reverse Linked List
Total Accepted: 5847 Total Submissions: 16863
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
用迭代来实现,思路定义一个前驱指针指向当前节点的前一节点,将当前节点后继指向前驱,前驱和当前指针同时后移,指导当前指针指向空。
/**
* 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) {
ListNode* pre; //定义当前节点的前驱
ListNode* cur; //定义指向当前节点指针
if(!head)return NULL;//头结点为空,直接返回空
pre=NULL;
cur=head;
while(cur){
ListNode* next;
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
head=pre;
}
};
//iteratively
Reverse Linked List
Submission Details
27 / 27 test cases passed.
Status: Accepted
Runtime: 10 ms