一、相交链表
自己答案:
/**
* 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集合
HashSet<ListNode> map=new HashSet<>();
map.add(headB);
ListNode temp=headB;
map.add(temp);
//遍历链表B,将每一个结点放入集合中
while(temp.next!=null){
temp=temp.next;
map.add(temp);
}
ListNode temp2=headA;
//通过遍历链表A,判断是否有结点已经存在于Set集合中
//有:交点
//没有:返回null
while(temp2!=null){
if(map.contains(temp2)){
return temp2;
}else{
temp2=temp2.next;
}
}
return null;
}
}
标准答案:
/**
* 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){
//如果链表为null则不可能有交点
//返回null
return null;
}else{
ListNode pA=headA;
ListNode pB=headB;
while(pA!=pB){
//链表长度分别为 a b
//不相交:两个指针经过了 a+b 次后同时到达null
//相交:两个指针经过了x(<a+b)次后到达交点
pA=pA==null?headB:pA.next;
pB=pB==null?headA:pB.next;
}
return pA;
}
}
}
二、反转链表
自己答案:
/**
* 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) {
if(head==null){
return null;
}else{
ListNode L=null;
ListNode R=head;
ListNode temp=head.next;
while(temp!=null){
R.next=L;
L=R;
R=temp;
temp=temp.next;
}
head=R;
head.next=L;
}
return head;
}
}
标准答案:
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
知识点:
链表A-B-C-D中temp为 A.next 表示 temp是结点B ,修改A.next=C不会导致temp为C
三、回文链表
自己代码:
/**
* 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 boolean isPalindrome(ListNode head) {
if(head==null){
return false;
}
ArrayList<Integer> list=new ArrayList<>();
list.add(head.val);
ListNode temp=head.next;
while(temp!=null){
//遍历链表放入集合中
list.add(temp.val);
temp= temp.next;
}
int index=list.size()-1;
int i=0;
while(((i-index)!=1)&&((i-index)!=0)) {
//两种情况,奇数和偶数
// i-index==1 表示两个索引已经交换了位置
// i==index 表明两个索引重合
if (list.get(i) != list.get(index)) {
return false;
} else {
i++;
index--;
}
}
return true;
}
}
标准答案:
太麻烦了,不想记