目录
141.环形链表
题目描述:给定一个链表,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。如果链表中存在环,则返回 true 。 否则,返回 false 。
解法1:将节点存放到HashSet中,存放时判断是否有重复的,如果存在重复说明有环。
public boolean hasCycle(ListNode head) {
//HashSet中不允许重复,将所有的节点存放进去,如果重复,则有环
HashSet<ListNode> hashSet=new HashSet<ListNode>();
while(head!=null){
boolean b=hashSet.add(head);
if(b==false){
return true;
}
head=head.next;
}
return false;
}
解法2:快指针和慢指针
慢指针针每次走一步,快指针每次走两步,如果相遇就说明有环,如果有一个为空说明没有环。
(只要两个指针的步数不同即可)
if(head==null){//链表为空单独来说
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast){
return true;
}
}
return false;
21.合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
方法1:因为链表是升序的,我们只需要遍历每个链表的头,比较一下哪个小就把哪个链表的头拿出来放到新的链表中,一直这样循环,直到有一个链表为空,然后我们再把另一个不为空的链表挂到新的链表中。
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
//两个均不为空
ListNode head=new ListNode();//头节点中存储的为0
head.next=null;
ListNode node=head;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
node.next=l1;
node=node.next;
l1=l1.next;
}else{
node.next=l2;
node=node.next;
l2=l2.next;
}
}
if(l1!=null){
node.next=l1;
}
if(l2!=null){
node.next=l2;
}
return head.next;
}
解法2:使用递归
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//递归方法解决:
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
//两个均不为空,使用递归
if(l1.val<=l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
234.回文链表
给你一个单链表的头节点 head
,请你判断该链表是否为回文链表。如果是,返回 true
;否则,返回 false
。
1.使用栈,将所有的节点值入栈,相当于从后向前读,如果和从头开始一样的话,那么是回文串
public boolean isPalindrome(ListNode head) {
// //使用栈解决,将所有的节点入栈,相当于从后向前读,如果和从头开始一样的话,那么是回文串
Stack<Integer> stack=new Stack();
ListNode listnode=head;
while(listnode!=null){
stack.push(listnode.val);//入栈
listnode=listnode.next;
}
while(head!=null){
if(head.val==stack.pop()){
head=head.next;
}else{
return false;
}
}
return true;
}
2.反转链表的后半部分,如果前半部分和后半部分相同,那么是回文串。
public boolean isPalindrome(ListNode head) {
ListNode node=head;
int count=0;
while (node!=null){
count++;
node=node.next;
}//计算链表的长度
System.out.println(count);
if(count%2!=0){//奇数个
count=(count+1)/2;
}else{
count=count/2+1;
}
node=head;
for(int i=1;i<count;i++){
node=node.next;
}//此时node指向后半部分第一个节点
node=reverse(node);//反转后半部分
System.out.println(node);
while(head!=null&&node!=null){
if(head.val!=node.val){
return false;
}else {
head=head.next;
node=node.next;
}
}
return true;
}
public ListNode reverse(ListNode node){//反转链表
ListNode node1=node.next;
node.next=null;
ListNode temp;
while(node1!=null){
temp=node1;
node1=node1.next;
temp.next=node;
node=temp;
}
return node;
}