1.合并两个有序链表:
21. 合并两个有序链表 - 力扣(LeetCode)
public ListNode mergeTwoLists(ListNode headA, ListNode headB){ListNode newhead=new ListNode(-1);ListNode cur=newhead;while(headA!=null&&headB!=null){if(headA.val<headB.val){cur.next=headA;headA=headA.next;cur=cur.next;}else{cur.next=headB;headB=headB.next;cur=cur.next;}}
if(headA==null){cur.next=headB;
}
if(headB==null){cur.next=headA;
}
return newhead.next;
}
2.链表的分割:
链表分割_牛客题霸_牛客网 (nowcoder.com)
public ListNode partition(ListNode pHead, int x) {if(pHead==null){//如果链表为空,则提前返回return null;}ListNode bs=null;ListNode be=null;ListNode as=null;ListNode ae=null;ListNode cur=pHead;while(cur!=null){//开始遍历链表if(cur.val<x){//第一种情况if(bs==null){//第一次插入bs=be=cur;}else{be.next=cur;be=be.next;}}else{//第二种情况if(as==null){//第一次插入as=ae=cur;}else{ae.next=cur;ae=ae.next;}}cur=cur.next;}if(bs==null){//如果没有小于x的节点,直接返回大于等于x的节点return as;}if(as!=null){//如果大于x的节点不为空ae.next=null;}be.next=as;//绑定两段链表return bs;}
3.链表的回文结构:
链表的回文结构_牛客题霸_牛客网 (nowcoder.com)
public boolean chkPalindrome(ListNode A) {ListNode slow=A;ListNode fast=A;while(fast!=null&&fast.next!=null){//开始找中间节点slow=slow.next;fast=fast.next.next;}ListNode cur=slow.next;while(cur!=null){//开始反转slow后面的链表ListNode curN=cur.next;cur.next=slow;slow=cur;cur=curN;}while(A!=slow){//一个从头开始走,一个从尾开始走if(A.val!=slow.val){//一旦两值不相同,返回falsereturn false;}if(A.next==slow){//前提在值相同的情况下,偶个节点的情况return true ; }A=A.next;slow=slow.next;}return true ;//能走到这一步,返回真}
4.相交链表:
160. 相交链表 - 力扣(LeetCode)
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {if(headA==null||headB==null){//两个链表有一个为空,就返回nullreturn null;}ListNode pl=headA;ListNode ps=headB;int a=0,b=0;while(pl!=null){//分别求各链表的长度pl=pl.next;a++;}while(ps!=null){ps=ps.next;b++;}pl=headA;//重新指向头结点ps=headB;if(a<b){//使pl一直指向长的链表,ps指向短的链表pl=headB;ps=headA;}int len=a>b?(a-b):(b-a);while(len!=0){//移动长链表到合适的位置pl=pl.next;len--;}while(pl!=null&&ps!=null){//同时遍历两个链表if(ps==pl){//相遇提前返回return ps;}ps=ps.next;pl=pl.next;}return null;}
5.环形链表:
141. 环形链表 - 力扣(LeetCode)
public boolean hasCycle(ListNode head) {ListNode slow=head;ListNode fast=head;while(fast!=null&&fast.next!=null){//开始遍历链表fast=fast.next.next;//快指针走两步slow=slow.next;//慢指针走一步if(slow==fast){//如果相遇return true;}}return false;//不相遇}
6.环形链表2:
142. 环形链表 II - 力扣(LeetCode)
public ListNode detectCycle(ListNode head) {if(head==null){//如果链表为空return null;}ListNode slow=head;ListNode fast=head;while(fast!=null&&fast.next!=null){//开始找相遇节点fast=fast.next.next;//快指针走两步slow=slow.next;//慢指针走一步if(slow==fast){//如果相遇break;}}if(fast==null||fast.next==null){//判断链表是否成环return null;}slow=head;//重置slow节点,此时fast节点指向相遇点while(slow!=fast){slow=slow.next;fast=fast.next;}return slow;}