206. Reverse Linked List

question:

Reverse a singly linked list.

answer:

使用三个指针遍历单链表,逐个链接点进行反转。

/**
 * 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 *p;
        ListNode *q;
        ListNode *r;
        if(head==NULL||head->next==NULL){
            return head;
        }
        p=head;
        q=p->next;
        head->next=NULL;
        while(q!=NULL){
            r=q->next;
            q->next=p;
            p=q;
            q=r;
        }
        head=p;
        return head;
    }
};

 

posted @ 2016-06-28 19:09  绵绵思远道  阅读(121)  评论(0编辑  收藏  举报