Java 链表反转:反转链表中前 K 个节点 - 代码示例和测试用例
public class CountDown {\n public class ListNode{\n int val;\n ListNode next;\n public ListNode(int x){\n x = val;\n }\n }\n public ListNode reverseList(ListNode head , int k){\n ListNode front = head , behind = head;//定义快慢指针,此时都指向头节点\n while(front !=null && k > 0){//判断链表不为空,并且k的值得为正数\n front = front.next;//只要链表不为空并且k>0,front就一直往下走\n k--;//front走一步k-1\n }\n while(front != null){\n front = front.next;\n behind = behind.next;\n }\n return behind;\n }\n public ListNode buildLinkedList(int[]arr){\n ListNode dummy = new ListNode(0);//创建一个虚拟头结点,值为0,作为链表的起始点。\n ListNode curr = dummy;//创建一个指针curr,指向当前节点,初始时指向虚拟头结点。\n for (int nums:arr) {\n curr.next = new ListNode(nums);\n curr = curr.next;\n }\n return dummy.next;\n }\n public static void main(String[] args) {\n CountDown countDown = new CountDown();\n \n // Test case 1: Reverse a linked list with k = 3\n int[] arr1 = {1, 2, 3, 4, 5};\n ListNode head1 = countDown.buildLinkedList(arr1);\n ListNode reversed1 = countDown.reverseList(head1, 3);\n printLinkedList(reversed1); // Output: 3 -> 2 -> 1 -> 4 -> 5\n \n // Test case 2: Reverse a linked list with k = 1\n int[] arr2 = {1, 2, 3, 4, 5};\n ListNode head2 = countDown.buildLinkedList(arr2);\n ListNode reversed2 = countDown.reverseList(head2, 1);\n printLinkedList(reversed2); // Output: 1 -> 2 -> 3 -> 4 -> 5\n \n // Test case 3: Reverse a linked list with k = 6 (greater than length of list)\n int[] arr3 = {1, 2, 3, 4, 5};\n ListNode head3 = countDown.buildLinkedList(arr3);\n ListNode reversed3 = countDown.reverseList(head3, 6);\n printLinkedList(reversed3); // Output: 1 -> 2 -> 3 -> 4 -> 5\n }\n \n public static void printLinkedList(ListNode head) {\n ListNode curr = head;\n while (curr != null) {\n System.out.print(curr.val + " -> ");\n curr = curr.next;\n }\n System.out.println("null");\n }\n}
原文地址: https://www.cveoy.top/t/topic/pYyK 著作权归作者所有。请勿转载和采集!