java 链表转置
Posted 王小豆的烂笔头
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 链表转置相关的知识,希望对你有一定的参考价值。
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 链表转置的主要内容,如果未能解决你的问题,请参考以下文章