方法1:
遍历原链表,把每个遍历到的节点头插到新链表
Node reverse(Node head){
Node cur = head;
Node newHead = null;
while(cur != null){
//记录cur的下一节点
Node next = cur.next;
//头插
cur.next = newHead;
newHead = cur;
cur = next;
}
return newHead;
}
方法2:
三个指针向后遍历
Node reverse2(Node head){
if (head ==null){
return null;
}
Node p1 = null;
Node p2 = head;
Node p3 = head.next;
while(p2 != null){
p2.next = p1;
p1 = p2;
p2 = p3;
if (p3!=null){
p3 = p3.next;
}
}
return p1;
}
//简化
Node reverse3(Node head){
Node p1 = null;
Node p2 = head;
while(p2 != null){
Node p3 = p2.next;
p2.next = p1;
p1 = p2;
p2 = p3;
}
return p1;
}