方法一:普通遍历
public class Test {
public ListNode ReverseList(ListNode head) {
if(null == head || null == head.next) return head;
ListNode pre = null;
ListNode cur = head;
while(null != cur){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
System.out.println(new Test().ReverseList(head).toString());
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
ListNode(int val,ListNode next){
this.next = next;
this.val = val;
}
@Override
public String toString() {
return "ListNode{" +
"val=" + val +
", next=" + next +
'}';
}
}
方法二:使用栈的特性,先进后出