问题:
- 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
解决:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
//1、利用链表反转
class Solution {
public ListNode reverseList(ListNode head) {
// 使用两个链表进行
ListNode pre=null;
ListNode cur=head;
while(cur!=null){
ListNode next=cur.next; //将cur剩下结点存到next中
cur.next=pre; //cur.next指向pre
pre=cur; //将pre指向cur 这几步完成了将cur中的结点以反序赋给pre
cur=next; //将原本剩下的结点重新还给cur
}
return pre;
}
}
//反转该链表并输出反转后链表的头节点
![]()
//2、使用栈解决
class Solution{
public ListNode reverseList(ListNode head){
//利用栈进行反转
if(head==null) return head;
// 1.首先要将链表中的结点放到栈中
Stack<ListNode> stack=new Stack<ListNode>();
ListNode cur=head;
while(cur!=null){
stack.push(cur);
cur=cur.next;
}
// 2。再将栈中的结点拿出
ListNode pre=stack.pop();
ListNode nex=pre;
nex.next=null; //创建两条相交链表
while(!stack.empty()){
nex.next=stack.pop(); //让nex.next不断的指向新结点,将结点添加到相交链中,然后将nex向后移动
nex=nex.next;
nex.next=null;
}
return pre;
}
}
// 3、递归!!
class Solution{
public ListNode reverseList(ListNode head){
if(head==null||head.next==null) return head;
ListNode newHead= reverseList(head.next);
head.next.next=head;
head.next=null;
return newHead;
}
}
![]()
总结
- 使用栈的想法最简单,但是要注意怎么将栈中的单个结点正确的链接到链表上
- 递归想法最抽象,需要注意避免出现环,递归结束条件