您的位置:首页 > 其它

单链表反转

2015-09-10 15:15 197 查看
给定一个单链表,实现单链表的反转

/**
* 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 || head->next==NULL)
return head;
ListNode *p=head,*q=NULL,*r=NULL; //三指针法
if(p->next!=NULL)
q=p->next; //q始终指向当前要
if(q->next!=NULL)
r=q->next;
bool first = true;
while(q!=NULL)
{
q->next=p;
if(first)
{
p->next=NULL;
first=false;
}
p=q;
q=r;
if(r!=NULL)
r=r->next;
}
head=p;
return head;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: