首页 > 编程语言 > 详细

java 链表转置

时间:2020-05-11 20:50:43      阅读:40      评论:0      收藏:0      [点我收藏+]

public class Test {

public static void main(String[] args) {
ListNode listNode = new ListNode(1);
int n = 2;
ListNode head = listNode;
while (n < 10) {
head.next = new ListNode(n);
head = head.next;
n++;
}
printfListNode(listNode);
reverseBetween(listNode, 2, 4);
printfListNode(listNode);
}

public static class ListNode {
int value;
ListNode next;

public ListNode(int value) {
this.value = value;
}
}

public static void printfListNode(ListNode listNode) {
ListNode head = listNode;
while (null != head.next) {
System.out.println(head.value);
System.out.println(",");
head = head.next;
}
}

public static ListNode reverseBetween(ListNode head, int m, int n) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode pre = dummy;
for (int i = 0; i < m; i++) {
pre = pre.next;
}
head = pre.next;
System.out.println(dummy);
for (int i = m; i < n; i++) {
ListNode nex = head.next;
head.next = nex.next;
nex.next = pre.next;
pre.next = nex;
}
return dummy.next;
}
}

java 链表转置

原文:https://www.cnblogs.com/mohanchen/p/12871430.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!