LeetCode day1 链表

一、206.反转链表:

cur:当前节点       head:头结点       next:储存当前节点的下一个节点   

 cur.next当前节点的下一个节点(后继节点)    pre:当前节点的上一个节点(前驱结点)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head,pre=null;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
}

二、160.相交链表

解法1、Hashset(无序、不重复、无索引)

将listA中的所有元素添加到集合visited中,遍历listB中元素,直至有元素属于listA,则该元素为相交节点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> visited = new HashSet<ListNode>();
        ListNode temp = headA;
        while (temp != null) {
            visited.add(temp);
            temp = temp.next;
        }
        temp = headB;
        while (temp != null) {
            if (visited.contains(temp)) {
                return temp;
            }
            temp = temp.next;
        }
        return null;
    }
}

解法2、不管长度相不相等两个链表第一次遍历完后,指针pA,pB为头结点的链表长度相同,俩链表元素同步对比,直至找到相交节点

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if(headA==null||headB==null){
                return null;
            }
            ListNode pA=headA,pB=headB;
            while(pA!=pB){
                pA=pA==null?headB:pA.next;
                pB=pB==null?headA:pB.next;
            }
            return pA;
        }
}

三、Collection中常用方法

所有单列集合都可以继承使用Collection接口中的方法

1、添加
 boolean add()

 addAll()

2、获取有效元素的个数
 int size()

3、清空集合
 void clear()

4、是否是空集合
 boolean isEmpty()

5、是否包含某个元素
 boolean contains(Object obj)

6、删除
 boolean remove(Object obj) 

7、集合是否相等
 boolean equals(Object obj)

  • 18
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值