【LeetCode】27.Linked List—Reverse Linked List l链表逆置

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

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 *p=head;        //定义指向头节点的指针
        if(p==NULL) return NULL; //使用前判断是否为空指针
        ListNode *q=p->next;     //定义第二个指针始终指向P的next
        while(p!=NULL&&q!=NULL)
        {
            p->next=q->next;
            q->next=head;
            head=q;
            q=p->next;
        }
        return head;
    }
};

 

posted @ 2019-08-29 14:48  蓝天下的一棵草  阅读(258)  评论(0)    收藏  举报