Leetcode: Reverse Linked List

linkedlist,iterative seems much easier than recursive

  1. Reverse Linked List
    https://leetcode.com/problems/reverse-linked-list/description/
/**
 * 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* next;
        ListNode* pre = NULL;
        ListNode* cur = head;
        while(cur)
        {
            next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        
        return pre;
    }
};

每次写链表,很容易在赋值中凌乱,
比如上面的:
next = cur->next; //把cur->next(也就是下一个node)赋值给next
cur->next = pre; //把pre(也就是上一个node)赋值给cur->next,也就是改变了cur->next的指向,从以前的next指向了pre
所以:
如果讨论赋值的话,就是从右往左
如果讨论指针指向的话,就是从左往右
或者:
cur->next在右边就是指的是下一个节点
cur->next在左边就是cur的next pointer
一般都是先把原来的linked node存下来,然后再改变指向,就把原来的link break了
pre = cur; //把cur赋值给pre,也就是pre移到下一个节点
cur = next; //把next赋值给cur,也就是把cur移到下一个节点

比如下面的:
newhead = reverseList(head->next);// newhead就是原list的tail
head->next->next = head;//head->next其实是reversed list的tail,tail->next指向原来的head,原来的head就变成了新list的tail
head->next = NULL; //最后指向nULL

        ListNode* newhead;
        if(head == NULL || head->next == NULL)
        {
            return head;
        }
        
        newhead = reverseList(head->next);
        head->next->next = head;
        head->next = NULL;
        
        return newhead;

猜你喜欢

转载自blog.csdn.net/weixin_43476349/article/details/84197401