Problem
https://leetcode.com/problems/reverse-linked-list-ii/description/
Solution
/**
* 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 reverseBetween(ListNode head, int left, int right) {
ListNode dummy = new ListNode();
dummy.next = head;
ListNode before = dummy;
for (int i=1;i<left;i++) {
before = before.next;
}
ListNode prev = before;
ListNode curr = before.next;
ListNode nextNode = null;
for (int i=left;i<=right;i++) {
nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
before.next.next = curr;
before.next = prev;
return dummy.next;
}
}
- before 포인터를 유지하면서 reverse 하기 전 노드의 위치를 저장해 놓는 것이 중요하다!
- reverse linked list 는 prev, curr, next 3 개의 포인터를 유지하면서 순회하는 것이 중요.

Pseudo Code – Reversing a linked list
ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextNode = curr.next; // first, make sure we don't lose the next node
curr.next = prev; // reverse the direction of the pointer
prev = curr; // set the current node to prev for the next node
curr = nextNode; // move on
}
return prev;
}

Leave a comment