题目:
Reverse a singly linked list.
分析:
反转链表。设置一个tail链表,对于所求链表的每个到来的节点都利用next将tail连起来。
代码:
/**
* 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* tail=NULL;
ListNode* tmpHead=head;
while(tmpHead!=NULL){
ListNode *tmp=new ListNode(tmpHead->val);
tmp->next=tail;
tail=tmp;
tmpHead=tmpHead->next;
}
return tail;
}
};