public class reverseList {
public static void main(String[] args) {
ListNode one = new ListNode(1);
ListNode two = new ListNode(2);
ListNode three = new ListNode(3);
ListNode four = new ListNode(4);
ListNode five = new ListNode(5);
one.next = two;
two.next = three;
three.next = four;
four.next = five;
five.next = null;
printLink(one);
ListNode head = reverseList(one);
printLink(head);
}
public static void printLink(ListNode head) {
if (null == head) System.out.println("head is null");
while (head != null) {
System.out.println(head.val);
head = head.next;
}
}
public static ListNode reverseList(ListNode head) {
if (head == null || head.next == null) return head;
ListNode prev = null;
while (null != head) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
}
复制代码
反转一个单链表。
最新推荐文章于 2020-09-23 14:58:17 发布