反轉單連結串列Assume that we have linked list 1 > 2 > 3 > 0, we would like to change it to 0 > 1 > 2 > 3./** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x;
兩兩交換單連結串列中的節點/Swap Nodes in PairsGiven a linked list, swap every two adjacent nodes and return its head.Given 1-> 2-> 3-> 4, you should return the list as 2-> 1-> 4-> 3./** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x;
判斷連結串列是否有環/Linked List CycleGiven a linked list, determine if it has a cycle in it.To represent a cycle in the given linked list, we use an integer pos which represents the position(0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list./** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } *///使用Set自動判重public class Solution { publicbooleanhasCycle(ListNode head){ Set< ListNode> set = new HashSet< ListNode> (); while(head != null){ if(set.contains(head)){ returntrue;
Linked List Cycle IIGiven a linked list, return the node where the cycle begins. If there is no cycle, returnnull.To represent a cycle in the given linked list, we use an integer pos which represents the position(0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.Note: Do not modify the linked list./** * 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){ Set< ListNode> set = new HashSet< ListNode> (); while(head != null){ if(!set.add(head)){ return head;
} head = head.next;
} returnnull;
} }複製程式碼
Reverse Nodes in k-GroupGiven a linked list, reverse the nodes of a linked list k at a time and return its modified list.k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.Example:Given this linked list: 1-> 2-> 3-> 4-> 5For k = 2, you should return: 2-> 1-> 4-> 3-> 5For k = 3, you should return: 3-> 2-> 1-> 4-> 5Note:Only constant extra memory is allowed.You may not alter the values in the list's nodes, only nodes itself may be changed./** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x;