给一个单向链表以及整数N,使得每N个元素为一组进行翻转。要求时间复杂度O(n), 空间复杂度O(1)。
示例1
输入
{1,2,3,4,5,6,7,8},3
输出
{3,2,1,6,5,4,8,7}
加载中...
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * reverse the given linked list * @param head ListNode类 the head of the linked list * @param n int整型 the N * @return ListNode类 */ public ListNode reverseLinkedList (ListNode head, int n) { // write code here } }
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ class Solution { public: /** * reverse the given linked list * @param head ListNode类 the head of the linked list * @param n int整型 the N * @return ListNode类 */ ListNode* reverseLinkedList(ListNode* head, int n) { // write code here } };
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # reverse the given linked list # @param head ListNode类 the head of the linked list # @param n int整型 the N # @return ListNode类 # class Solution: def reverseLinkedList(self , head , n ): # write code here
/* * function ListNode(x){ * this.val = x; * this.next = null; * } */ /** * reverse the given linked list * @param head ListNode类 the head of the linked list * @param n int整型 the N * @return ListNode类 */ function reverseLinkedList( head , n ) { // write code here } module.exports = { reverseLinkedList : reverseLinkedList };
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # reverse the given linked list # @param head ListNode类 the head of the linked list # @param n int整型 the N # @return ListNode类 # class Solution: def reverseLinkedList(self , head , n ): # write code here
package main import . "nc_tools" /* * type ListNode struct{ * Val int * Next *ListNode * } */ /** * reverse the given linked list * @param head ListNode类 the head of the linked list * @param n int整型 the N * @return ListNode类 */ func reverseLinkedList( head *ListNode , n int ) *ListNode { // write code here }
/** * struct ListNode { * int val; * struct ListNode *next; * }; */ /** * reverse the given linked list * @param head ListNode类 the head of the linked list * @param n int整型 the N * @return ListNode类 */ struct ListNode* reverseLinkedList(struct ListNode* head, int n ) { // write code here }
{1,2,3,4,5,6,7,8},3
{3,2,1,6,5,4,8,7}