翻转链表
Meteor
2023-06-01 18:09:37
92 翻转链表||
解题思路1
整个链表可以分成三段,1-left-1、left-right、right-end,只需要用栈存储从left到right的节点,然后一个个弹出栈,逆序连接在一起,然后将三段拼接在一起即可。
代码
class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if(left==right) return head; ListNode pre = new ListNode(); pre.next = head; ListNode res = pre; int count = 1; Stack<ListNode> stack = new Stack<>(); while(count<left){ pre = pre.next; count++; } ListNode cur = pre.next; while(count<=right){ stack.add(cur); cur = cur.next; count++; } while(!stack.isEmpty()){ pre.next = stack.pop(); pre = pre.next; } pre.next = cur; return res.next; } }
|
解题思路2
不使用栈,直接将从left到right的节点逆序连接,然后将三个部分连接在一起即可。
代码
class Solution { public ListNode reverseBetween(ListNode head, int left, int right) { if(left==right) return head; ListNode pre = new ListNode(); pre.next = head; ListNode res = pre; int count = 1; while(count<left){ count++; pre = pre.next; } ListNode cur = pre.next; ListNode first = cur; ListNode next = cur.next; cur.next = null; while(count<right){ ListNode temp = next.next; next.next = cur; cur = next; next = temp; count++; } pre.next = cur; first.next = next; return res.next; } }
|
总结
链表一般定义一个pre头节点进行处理会更加方便