输入一个链表,反转链表后,输出链表的所有元素。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head == null) return null;
if(head.next == null) return head;
ListNode p = head, q = head.next, temp = q.next;
head.next = null;
while(true){
q.next = p;
p = q;
q = temp;
if(q == null)
break;
temp = temp.next;
}
return p;
}
}
三个指针在链表上移动,唯一要注意的是循环终止条件