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;}