您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法
反转链表(图文)
第十三双眼睛2023-12-03【数据结构与算法】人已围观
简介反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
思路:在遍历链表时,将当前节点的 next 指针改为指向前一个节点。由于节点没有引用其前一个节点,因此必须事先存储其前一个节点。在更改引用之前,还需要存储后一个节点。最后返回新的头引用。代码如下:
public static ListNode method1(ListNode head) { if (head == null || head.next == null) { return head; } ListNode pre = null; ListNode next = null; ListNode current = head; while (current != null) { next = current.next; current.next = pre; pre = current; current = next; } return pre; } |
Tags:
很赞哦! ()
上一篇:同构字符串(图文)
下一篇:存在重复元素(图文)