如果节点总数不是 k 的整数倍,那么请将最后剩余的节点保持原有顺序。
给定这个链表:1->2->3->4->5
当 k = 2 时,应当返回: 2->1->4->3->5
当 k = 3 时,应当返回: 3->2->1->4->5
第一行:依次输入链表中的各个元素,以"#"结束
第二行:每组数量k
处理后的链表中的各个元素,以"->"连接
1 2 3 4 5 # 2
2->1->4->3->5
1 2 3 4 5 # 3
3->2->1->4->5
import java.util.*; public class Main { static class ListNode{ int val; ListNode next; ListNode(int val){ this.val = val; } } // 这里全是输入处理 public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ String str = in.nextLine(); int k = in.nextInt(); ListNode head = new ListNode(-1); ListNode p = head; String[] strArray = str.split(" "); for(int i = 0; i < strArray.length - 1; i++){ p.next = new ListNode(Integer.parseInt(strArray[i])); p = p.next; } head = reverseK(head.next, k); printList(head); } } // 输出处理 private static void printList(ListNode head) { while(head != null){ System.out.print(head.val); if(head.next != null){ System.out.print("->"); } head = head.next; } } // 核心程序 private static ListNode reverseK(ListNode head, int k) { if(k == 1 || head == null || head.next == null){ return head; } ListNode a = head, b = head; for(int i = 0; i < k; i++){ if(b == null){ return head; } b = b.next; } ListNode newHead = reverse(a, b); head.next = reverseK(b, k); return newHead; } private static ListNode reverse(ListNode a, ListNode b) { ListNode pre = null, cur = a; while(cur != b){ ListNode next = cur.next; cur.next = pre; pre = cur; cur = next; } return pre; } }
//leetcode25. K 个一组翻转链表 const readline = require('readline') const rl = readline.createInterface({ input: process.stdin, ouput: process.stdout }) let inArr = [] rl.on('line',line=>{ if(!line) return inArr.push(line.trim()) if(inArr.length === 2){ let arr = inArr[0].split(' ').map(e=>+e) arr.pop() let k = +inArr[1] let res= reverseKGroup(arr, k).join('->') console.log(res) } }) var reverseKGroup = function(arr, k) { let len = arr.length let cnt = Math.floor(len/k) let curArr = [...arr] for (let i = 0; i < cnt; i++) { let lastArr = curArr.slice(k*(i+1)) curArr = curArr.slice(0,i*k).concat(curArr.slice(i*k,k*(i+1)).reverse(),lastArr) } return curArr };
import java.util.Scanner; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { static class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; } } public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNext()) { // 注意 while 处理多个 case String arrayStr = in.nextLine(); int k = in.nextInt(); ListNode head = new ListNode(0); ListNode p = head; String[] array = arrayStr.split(" "); for (int i = 0; i < array.length - 1; i++) { p.next = new ListNode(Integer.parseInt(array[i])); p = p.next; } // 反转链表 head = reverseK(head.next, k); printList(head); } } private static ListNode reverseK(ListNode head, int k) { // 如果反向反转 此处需要将整个链表反转 ListNode dummy = new ListNode(-1); dummy.next = head; ListNode pre = dummy; ListNode end = dummy; // 循环操作 while (end.next != null) { for (int i = 0; i < k && end != null; i++) { end = end.next; } if (end == null) { break; } // 开始切断连线 ListNode start = pre.next; ListNode nextStart = end.next; end.next = null; pre.next = reverseKGroup(start); start.next = nextStart; pre = start; end = pre; } return dummy.next; } // 反转链表 改变指针方向 private static ListNode reverseKGroup(ListNode head) { ListNode pre = null; ListNode curr = head; while (curr != null) { ListNode next = curr.next ; curr.next = pre; pre = curr; curr = next; } return pre; } /** * 2->1->4->3->5 */ private static void printList(ListNode head) { StringBuilder sd = new StringBuilder(); while (head != null) { sd.append(head.val); head = head.next; if (head != null ) { sd.append("->"); } } System.out.println(sd.toString()); } }
import java.util.*; public class Main{ public static void reverse(String[] str,int start,int end){ while(start < end){ String temp = str[start]; str[start] = str[end]; str[end] = temp; start++; end--; } } public static void main(String[] args){ Scanner sc = new Scanner(System.in); String str = sc.nextLine(); int n = sc.nextInt(); //将输入字符串以空格进行分隔 String[] strArr = str.split(" "); int start = 0; while(start + n - 1 < strArr.length - 1){ reverse(strArr,start,start + n - 1); start += n; } for(int i = 0;i < strArr.length - 2;i++){ System.out.print(strArr[i] + "->"); } //将最后一个数字打印输出 System.out.println(strArr[strArr.length - 2]); } }
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); ListNode dummy = new ListNode(); ListNode old = dummy; while(sc.hasNext()) { String in = sc.next().trim(); if(in.equals("#")) break; while(dummy.next != null) { dummy = dummy.next; } dummy.next = new ListNode(Integer.parseInt(in)); } int k = sc.nextInt(); ListNode head = solution(old.next,k); while(head.next != null) { System.out.print(head.val + "->"); head = head.next; } System.out.print(head.val); } private static ListNode solution(ListNode head, int k) { if(head == null) return head; int size = 0; for(ListNode i = head; i != null; i = i.next, size ++); ListNode dmy = new ListNode(), oldHead = dmy, cur = head, h; while(k <= size) { size -= k; for(int i = 0; i < k; i++) { h = cur; cur = cur.next; h.next = dmy.next; dmy.next = h; } while(dmy.next != null) { dmy = dmy.next; } } if(cur != null) dmy.next = cur; return oldHead.next; } static class ListNode { int val; ListNode next; ListNode(int val) { this.val = val; this.next = null; } ListNode() {} } }
while 1: try: inp = list(input().split()) inp = inp[0:len(inp)-1] h = len(inp) k = int(input()) n = h//k if n*k!=h: for ii in range(n): y = inp[k*ii:k*(ii+1)] y.reverse() print('->'.join(y),end='->') print('->'.join(inp[n*k:])) else: for ii in range(n-1): y = inp[k*ii:k*(ii+1)] y.reverse() print('->'.join(y),end='->') y = inp[k*(n-1):k*n] y.reverse() print('->'.join(y)) except: break能过,但写的很麻烦,有没有老哥可以不用分情况的
let nums = readline().split(' ').slice(0,-1) let k = readline() let res = [] let result = '' if(k<=1){ result = nums.join('->') }else{ while(nums.length>=k){ let arr = nums.splice(0,k) let ar=[] for(let i=0;i<k;i++){ let result = arr.shift() ar.unshift(result) } res.push(ar) } for(let i=0;i<res.length;i++){ if(i==res.length-1&&nums.length==0){ result+=res[i].join('-\>') }else{ result+=res[i].join('-\>')+'->' } } let back = nums.join('->') result = result+back } console.log(result)
//小渣渣直接用的list,输入输出很迷 import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); LinkedList<String> list = new LinkedList<>(); while(sc.hasNext()) { list.add(sc.next()); } int k = new Integer(list.getLast()); list.removeLast(); list.removeLast(); int len = list.size(); int m = len/k; List<String> res = new LinkedList<>(); for(int i=0; i<m*k;i+=k) { List<String> tmp = new LinkedList<>(); tmp.addAll(list.subList(i, i+k)); Collections.reverse(tmp); res.addAll(tmp); } res.addAll(list.subList(m*k, len)); for(int i=0; i<res.size()-1;i++) { System.out.print(res.get(i)+"->"); } System.out.print(res.get(len-1)); } }
//我是** import java.util.*; public class Main{ public static void main(String args[]) { Scanner scanner = new Scanner(System.in); ArrayList<String> arraylist = new ArrayList<>(); ArrayList<ArrayList<String>> arrayLists = new ArrayList<>(); while (scanner.hasNext()) { arraylist.add(scanner.next()); } int k = new Integer(arraylist.get(arraylist.size() - 1)); arraylist.remove(arraylist.size() - 1); arraylist.remove(arraylist.size() - 1); int j = 0; for (int i = 0; i < arraylist.size() / k; i++) { int n = 0; ArrayList<String> array = new ArrayList<>(); while (n < k) { array.add(arraylist.get(j)); n++; j++; } Collections.reverse(array); arrayLists.add(array); } String str = ""; for (int i = 0; i < arraylist.size() / k; i++) { for (int h = 0; h < k; h++) { str += arrayLists.get(i).get(h) + "->"; } } for (int i = j; i < arraylist.size(); i++) { if (i == arraylist.size() - 1) { str += arraylist.get(i); } else { str += arraylist.get(i) + "->"; } } //末尾为 -> if (k == 1 || k == arraylist.size()) { StringBuilder stringBuilder = new StringBuilder(str); stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length()); System.out.println(stringBuilder); } else { System.out.println(str); } } }
#include <iostream> #include <string> using namespace std; struct ListNode{ int val; ListNode* next; ListNode(int x):val(x),next(nullptr){} ListNode():val(0),next(nullptr){} }; ListNode* re(ListNode* head,int k){ // 下一组节点的首节点 ListNode* next_head=head; for(int i=0;i<k;++i){ // 该组长度小于k,不翻转,返回该组的首节点 if(!next_head){ return head; } next_head=next_head->next; } // 下一组节点翻转后的首节点 ListNode* next_reverse_head=re(next_head,k); for(int i=0;i<k;++i){ ListNode* nex=head->next; head->next=next_reverse_head; next_reverse_head=head; head=nex; } return next_reverse_head; } int main() { int k; int temp; cin >> temp; ListNode* head = new ListNode(temp); ListNode* cur = head; string t; while (cin >> t) { if (t=="#") { break; } ListNode* nex = new ListNode(stoi(t)); cur->next = nex; cur = cur->next; } cin >> k; ListNode* res_head = re(head, k); string res; while (res_head) { res += to_string(res_head->val); if (res_head->next) { res += "->"; } res_head = res_head->next; } cout << res << endl; }
package main import ( "fmt" "strconv" ) func solve(a []int, k int) { length := len(a) for i := 0; i < length; { if i+k-1 < length { for m,n := i, i+k-1; m < n; m,n = m+1, n-1 { a[m], a[n] = a[n], a[m] } } i = i+k } } func main(){ var nSlice = []int{} for { var temp = "" fmt.Scan(&temp) if temp == "#" { break } else { num, err := strconv.Atoi(temp) if err != nil { panic(err) } else { nSlice = append(nSlice, num) } } } var k = 0 fmt.Scan(&k) solve(nSlice, k) for i, value := range nSlice { fmt.Print(value) if i != len(nSlice)-1 { fmt.Print("->") } } }