题目:输入一个链表,反转链表后,输出新链表的表头。
解法一:
-
利用栈这种数据结构,先进后出的思想,循环遍历当前链表,将所有节点压入到栈中,那么最后遍历结束后,栈顶元素必为链表的尾结点。
-
再进行一次遍历,遍历当前的栈,直到栈不空为止,在遍历栈之前,要提前弹出当前栈顶元素,从第二个元素开始遍历栈,每弹出一个新的元素,就将上一个节点的next指向新弹出的节点,然后再将新弹出的元素保存在pointer指针中
-
最后关键一步,遍历完栈之后,一定要最后出栈的元素的next指针置位null,否则会导致反转的链表造成死循环。
public static ListNode reverseList(ListNode head) {
Stack<ListNode> stack = new Stack<ListNode>();
ListNode pointer=head;
while (pointer!=null) {
stack.push(pointer);
pointer=pointer.next;
}
if(!stack.isEmpty())
pointer=stack.pop();
else{
return null;
}
head=pointer;
while(!stack.isEmpty()){
ListNode node = stack.pop();
pointer.next=node;
pointer=node;
}
pointer.next=null;
return head;
}
解法二:
利用两个指针pre、next,其中pre保存当前最后一次反转的节点,next保存最后一次反转节点的下一次要反转的节点
//第二种高效率写法
public ListNode reverseList2(ListNode head) {
ListNode pre = null;
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}