Skip to content

Latest commit

 

History

History
71 lines (63 loc) · 1.42 KB

File metadata and controls

71 lines (63 loc) · 1.42 KB

题目描述:反转一个单链表

eg:

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

思路描述:遍历一遍,把后面的插前面就好

/**
 * 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* node = new ListNode(head->val);
        while(head->next){
            head = head->next;
            ListNode* h2 = new ListNode(head->val);
            h2->next = node;
            node = h2;
        }
        return node;
    }
};

双指针解法

定义两个指针: pre 和 cur ;pre 在前 cur 在后。 每次让 pre 的 next 指向 cur ,实现一次局部反转 局部反转完成之后, prep 和 cur 同时往前移动一个位置 循环上述过程,直至 pre 到达链表尾部

/**
 * 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* cur = NULL, *pre = head;
        while (pre != NULL) {
            ListNode* t = pre->next;
            pre->next = cur;
            cur = pre;
            pre = t;
        }
        return cur;
    }
};