LeetCode 翻转链表

基本思路

  1. 从元首节点之后每次取一个节点,并将节点接到元首节点前面

代码实现

/**
 * 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 * a = head;
        ListNode * c = head;
        ListNode * b = head->next;
        ListNode * t = NULL;
        while(b != NULL){
            //cout << b->val << endl;
            t = b->next;
            b->next = a;
            a = b;
            b = t;
            //cout << a->val << endl;
        }
        //一定要记得处理第一个指针,使其指向NULL,否则将出现无法终止的情况
        c->next = NULL;
        //cout << 1 << endl;
        return a;
    }
};
posted @ 2019-03-22 11:48  Phoenix_Xie  阅读(151)  评论(0编辑  收藏  举报