直接上代码(主要思想都在注释里面,就是需要三个类似指针(java又没有指针这一说,可以当作指针理解),一个个往后遍历,最后当前的节点为空时证明到尾部了)
public class singleLL {
public static void main(String[] args) {
ListNode head = new ListNode();
ListNode tail = head;
for (int i = 0; i < 10; i++) {
ListNode cur = new ListNode(i);
tail.next = cur;
tail = cur;
}
ListNode h = head.next;
while(h != null) {
System.out.print(h.val + " ");
h = h.next;
}
System.out.println();
head = head.next;
ListNode newHead = Solution.reverse(head);
h = newHead;
while(h != null) {
System.out.print(h.val + " ");
h = h.next;
}
}
public static class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static class Solution{
public static ListNode reverse(ListNode head){
ListNode pre = null; //存放当前节点的前一个节点
ListNode cur = head;//存放当前节点
ListNode next;//存放当前节点的后一个节点,防止当前节点指向自己的前一个节点时,后一个节点丢失
while(cur != null){
next = cur.next;//next保存当前节点的后一个节点
cur.next = pre; //实现链表反转,指向自己的前一个节点
pre = cur; //当前节点完成反转后,pre和cur都往后走一个位置
cur = next;
}
return pre;
}
}
}
运行结果: