-
问题描述
反转单链表。 -
解决方案
每到一个节点,就将该节点设为头部,将原来的头部设置为该节点的next节点。
public static Node invertLinkedList(Node head){
Node res;
if(head == null)
return null;
res = head;
Node cur = head.next;
head.next = null;//链表结尾置为空
while(cur != null){
Node temp = cur;
cur = cur.next;
temp.next = res;
res = temp;
}
return res;
}