一、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)