
两种方法来解决:(如果晕了,请在纸上画图分析,加深理解)
1)双指针


/**
* 反转:使用双指针
* @param head
* @return
*/
private static ListNode fun1(ListNode head) {
if (head == null){
return null;
}
ListNode cur = null; // 前
ListNode pre = head; // 后
while (pre != null){
ListNode temp = pre.next;
pre.next = cur;
cur=pre;
pre = temp;
}
return cur;
}
2)栈 “先进后出”
/**
* 反转:使用栈来完成,栈是“先进后出”
* @param head
* @return
*/
private static ListNode fun2(ListNode head) {
if (head == null){
return null;
}
Stack<ListNode> stack = new Stack<>();
// 遍历链表,将所有节点压入栈中
while (head != null){
stack.push(head);
head = head.next;
}
// 获得栈顶元素,作为链表头节点
if (!stack.isEmpty())
head = stack.pop();
ListNode cur = head; // 指针,便于插入元素的
while (!stack.isEmpty()){
ListNode node = stack.pop();
node.next = null;
cur.next = node;
cur = node;
}
return head;
}
本文介绍两种链表反转的方法:双指针法和栈法。双指针法通过前后两个指针相互交换实现反转,而栈法则利用栈的特性,先将链表元素全部压入栈中,再依次弹出构成新的链表。
627

被折叠的 条评论
为什么被折叠?



