剑指Offer打卡day13—— AcWing 35. 反转链表

【题目描述】

AcWing 35. 反转链表
在这里插入图片描述
【思路】
类比交换排序 对链表中元素值两两进行交换

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
     
        ListNode h = head;
        //链表长度
        int n = 0;
        while(h != null){
            h = h.next;
            n ++;
        }
        //n个节点 交换n - 1次
        
        int t = 0;
        while( t < n - 1){
            //p在前 q在后
            ListNode q = head;
            ListNode p = q.next;
            for(int i = 0; i < n - t - 1 ; i ++){
                //链尾
                if(p == null) continue;
                
                while( p != null && p != q){
                    //交换p、q节点元素值
                    int x = p.val;
                    p.val = q.val;
                    q.val = x;
                    //q前进
                    q = q.next;
                }
                //q赶上p了 p++
                p = p.next;
                
            }
                
            t ++;
        }
        
        return head;
    }
}

迭代

【思路】
翻转链表即将所有节点的next域指向其前驱节点。
由于是单链表,所以在迭代时不能直接找到前驱节点,所以需要一个额外的指针pre来保存前驱结点。在改变当前节点cur的next前,需要保存它的后继节点。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode h) {
        ListNode cur = h;
        ListNode pre = null;
        
        while(cur != null){
            //保存cur的后继
            ListNode tmp = cur.next;
            //将当前节点的后继修改为原来的前继
            cur.next = pre;
            //前继后移
            pre = cur;
            //cur后移
            cur = tmp;
        }
        return pre;
        
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值