ListNode 反向链表测试用例 一:ListNode 定义类 package LeetCode; public class ListNode { int val; ListNode next; ListNode(int x){ val = x; } } 二:ListNode反向链表实现类和测试用例 package LeetCode; import org.junit.Test; public class Solution2 { public ListNode reverseList(ListNode head){ ListNode cur = head,pre = null; while(cur != null ){ ListNode tmp = cur.next;//定义一个暂存变量tmp cur.next = pre;//修改引用指向 pre = cur; //pre暂存cur cur = tmp; //访问下一个节点 } return pre; } @Test public void testReverseList() { System.out.println("testReverseList"); ListNode head = new ListNode(1);//创建头节点 head.next = new ListNode(2);//再定义头节点的next域 ListNode t = head.next; for(int i=3;i<10;i++) {//创建一个简单的链表{1,2,3,4,5,...,9} t.next = new ListNode(i); t = t.next; } ListNode newHead = reverseList(head);//调用反转链表方法 System.out.println(newHead.val);//检查新的头节点的值 printListNode(newHead);//打印新链表的全部节点 } //为了便于查看结果,写的打印链表的方法 public void printListNode(ListNode head) { while(head!=null) { System.out.print(head.val+" "); head = head.next; } } }