(资料图)
/** * 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 swapPairs(ListNode head) { //只是用一个temp指针 ListNode dummyHead = new ListNode(); dummyHead.next = head; ListNode cur = dummyHead; while(cur.next != null && cur.next.next != null){ //临时指针存储cur的next,因为在操作后会变成孤立节点 ListNode temp = cur.next; //操作进行 cur.next = cur.next.next; temp.next = cur.next.next; cur.next.next = temp; //下一循环 cur = cur.next.next; } return dummyHead.next; }}
/** * 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 removeNthFromEnd(ListNode head, int n) { //双指针 ListNode dummyHead = new ListNode(); dummyHead.next = head; ListNode cur = dummyHead; ListNode post = dummyHead; while(n > 0){ post = post.next; if(post == null){ return null; } n--; } while(post.next != null){ post = post.next; cur = cur.next; } if(cur.next != null){ cur.next = cur.next.next; }else{ cur.next = null; } return dummyHead.next; }}
/** * 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) { ListNode curA = headA; ListNode curB = headB; int lenA = 0; int lenB = 0; while(headA != null){ headA = headA.next; lenA++; } while(headB != null){ headB = headB.next; lenB++; } headA = curA; headB = curB; if(lenA < lenB){ ListNode temp = headB; headB = headA; headA = temp; int tempInt = 0; tempInt = lenB; lenB = lenA; lenA = tempInt; } int gap = lenA - lenB; while(gap != 0){ headA = headA.next; gap--; } while(headA != null){ if(headA == headB){ return headA; } headA = headA.next; headB = headB.next; } return null; }}
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { //快慢指针,从快慢指针交界点开始与另一指针从头节点开始以相同速度进行,交点即为环入口 ListNode fast = head; ListNode slow = head; ListNode target = head; if(fast == null){ return null; } while(fast.next!= null &&fast.next.next !=null){ fast = fast.next.next; slow = slow.next; if(fast == slow){ break; } } if(fast.next == null||fast.next.next==null){ return null; } while(target != slow){ slow = slow.next; target = target.next; } return target; }}
关键词: