输入一个链表,反转链表后,输出新链表的表头java
提及反转,第一个想到的确定是利用栈先进后出的特性。这道题固然能够用栈来实现,可是对于注释中那一块不是很明白,先放着,若是有大佬知道的话求解答node
public class Solution { public ListNode ReverseList(ListNode head) { if (head == null) return null; Stack<ListNode> stack = new Stack<ListNode>(); ListNode temp = head; do { stack.push(temp); temp = temp.next; } while (temp != null); //若是这里的头结点的next要不置为空,就会致使遍历时无限循环 head.next = null; ListNode root = stack.pop(); ListNode node = root; while (!stack.isEmpty()) { node.next = stack.pop(); node = node.next; } return root; } }
最好的办法就是利用双指针的方式指针
public class Solution { public ListNode ReverseList(ListNode head) { if(head == null) return null; // head为当前节点,若是当前节点为空的话,那就什么也不作,直接返回null; ListNode pre = null; ListNode next = null; // 当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点 // 须要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2 // 即pre让节点能够反转所指方向,但反转以后若是不用next节点保存next1节点的话,此单链表就此断开了 // 因此须要用到pre和next两个节点 // 1->2->3->4->5 // 1<-2<-3 4->5 while(head!=null){ // 作循环,若是当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre // 如此就能够作到反转链表的效果 // 先用next保存head的下一个节点的信息,保证单链表不会由于失去head节点的原next节点而就此断裂 next = head.next; // 保存完next,就能够让head从指向next变成指向pre了,代码以下 head.next = pre; // head指向pre后,就继续依次反转下一个节点 // 让pre,head,next依次向后移动一个节点,继续下一次的指针反转 pre = head; head = next; } // 若是head为null的时候,pre就为最后一个节点了,可是链表已经反转完毕,pre就是反转后链表的第一个节点 // 直接输出pre就是咱们想要获得的反转后的链表 return pre; } }