链表-反转链表

代码随想录-刷题笔记

LCR 024. 反转链表 - 力扣(LeetCode)

还记得之前刚学数据结构那会被这道题吓蒙过,觉得这种题毫无意义,用双向链表可以一次性解决,之后发现这确实是很好的一道运用双...三指针的问题。

内容:

将一个链表反转,如果一个节点,需要满足三点

前置节点curPre , 该节点 cur , 后置节点 curNext

curPre -> next = curNext;

cur -> next = curNext -> next;

curNext -> next = cur;

链表-反转链表_第1张图片

只需要知道以上三点, 很显然需要三个指针, 要不然肯定是不够的.

代码可以轻易得出

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        while(cur!=null) {
            ListNode tmp = cur.next;
            cur.next = pre;
            pre = cur;
            cur = tmp;
        }
        return pre;
    }
}

 总结:

本题对于笔者个人而言确实有着非凡的意义。这道题可以说打开了算法的大门也不为过

实质上还是指针指向的问题而已..

你可能感兴趣的:(链表,数据结构)