码迷,mamicode.com
首页 > 编程语言 > 详细

java 链表转置

时间:2020-05-11 20:22:08      阅读:54      评论:0      收藏:0      [点我收藏+]

标签:nod   int   print   void   system   main   turn   链表   str   

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 链表转置

标签:nod   int   print   void   system   main   turn   链表   str   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!