7

反转链表II

 1 year ago
source link: https://stellarx.github.io/post/b17609ee.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

花 风 城市

反转链表II

发表于2022-05-17|更新于2022-05-18|算法与数据结构
字数总计:167|阅读时长:1分钟|阅读量:3
  • 用迭代不烧脑而且快,用递归烧脑而且占空间
  • 建一个辅助头节点dummy,可以让代码更简洁且方便

Java实现

/**
* 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(0, head);
ListNode pre = dummy, curr, rear;
for(int i = 1; i < left; ++i)
pre = pre.next;
head = pre;
pre = pre.next;
curr = pre.next;
for(int i = left; i < right; ++i){
rear = curr.next;
curr.next = pre;
pre = curr;
curr = rear;
}
head.next.next = curr;
head.next = pre;
return dummy.next;
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK