题意:反转一个单链表。
示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
双指针
public class Main {public static class ListNode {int val;ListNode next;ListNode(int x) {val = x;}}public ListNode reverseList(ListNode head) {ListNode prev = null;ListNode current = head;while (current != null) {ListNode nextNode = current.next;current.next = prev;prev = current;current = nextNode;}return prev;}public static void main(String[] args) {// 创建链表 1->2->3->4->5->NULLListNode head = new ListNode(1);head.next = new ListNode(2);head.next.next = new ListNode(3);head.next.next.next = new ListNode(4);head.next.next.next.next = new ListNode(5);head.next.next.next.next.next = null;// 反转链表并打印结果ListNode reversedHead = new Main().reverseList(head);while (reversedHead != null) {System.out.print(reversedHead.val + "->");reversedHead = reversedHead.next;}System.out.println("null");}
}