字节跳动------剑指offer专题精选谷歌、微软等知名IT企业典型面试题

73 篇文章 8 订阅

1. JZ6 从尾到头打印链表

输入:
{1,2,3}
返回值:
[3,2,1]

public ArrayList<Integer> printListFromTailToHead(ListNode listNode) {
        //用来存储链表中节点的值。
        Stack<Integer> reverse = new Stack<>();
        while(listNode != null){
            reverse.push(listNode.val);
            listNode = listNode.next;
        }
        //创建的题目要求的数据类型来存储反向的节点值。
        ArrayList<Integer> result = new ArrayList<>(); 
        while(!reverse.isEmpty()){
            //将值从栈中弹出,并添加到ArrayList中
            result.add(reverse.pop());
        }
        return result;
    }

2. 反转链表

public ListNode ReverseList(ListNode head) {
        if (head == null || head.next == null)
        return head;
        ListNode node = ReverseList(head.next);
        head.next.next = head;
        head.next = null;
        return node;
    }

3. 合并两个有序链表

public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1==null) return list2;
        if(list2==null) return list1;
        if(list1.val<list2.val){
            list1.next = Merge(list1.next,list2);
            return list1;
        } else {
            list2.next = Merge(list1,list2.next);
            return list2;
        }
    }

4 两个链表第一个公共节点

在这里插入图片描述

	public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
       ListNode l1 = pHead1, l2 = pHead2;
        while(l1 != l2){
            l1 = (l1==null)?pHead2:l1.next;
            l2 = (l2==null)?pHead1:l2.next;
        }
        return l1;
    }

5. 删除链表的某个节点

public ListNode deleteNode (ListNode head, int val) {
       while(head != null && head.val == val){
           head = head.next;
       }
        ListNode prev = head;
        if(prev!=null){
            while(prev.next!=null){
                if(prev.next.val == val){
                    prev.next = prev.next.next;
                }else{
                    prev = prev.next;
                }
            }
        }
        return head;
    }

6 删除链表重复节点

public ListNode deleteDuplication(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        //两个循环,用来应付“1-1-2-2-3-3-4-5…”格式的连续重复结点
        while(head != null && head.next != null && head.val == head.next.val){
            while(head != null && head.next != null && head.val == head.next.val){
                head = head.next;
            }
            head = head.next;
        }
        if(head!=null ){
            head.next = deleteDuplication(head.next);
        }
        return head;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coding路人王

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值