大模型可以翻转链表,但是只能翻转单个元素链表。一但牵扯到分组操作,就不会了。
Case:
以K个元素为一组位翻转链表,每一组内部元素顺序不变。
Reverse the chained table in group of K elements, don't change the order in each group.
Hand written:
1 class Node(): 2 def __init__(self, v=0, nxt = None) -> None: 3 self.value = v 4 self.nxt = nxt 5 def __str__(self) -> str: 6 return str(self.value) 7 8 class chain(): 9 def __init__(self, h=None,l=0) -> None: 10 self.head = h 11 self.len = l 12 13 def insert(self,v): 14 15 self.len+=1 16 n = self.head 17 if self.head is None: 18 self.head = Node(v) 19 else: 20 while n.nxt is not None: 21 n = n.nxt 22 n.nxt = Node(v) 23 def __str__(self): 24 n = self.head 25 res = [] 26 while n is not None: 27 res.append(n.value) 28 n = n.nxt 29 30 return ",".join([str(_) for _ in res]) 31 32 33 def reverse_(self,k): 34 35 if self.len < k: 36 return 37 prev = None 38 39 stay = self.head 40 cur = self.head 41 # stay 42 # cur 43 # nxt 44 # 1 2 3 4 5 6 7 45 while cur is not None: 46 47 nxt = cur.nxt 48 ct = k 49 print(cur) 50 while ct-1 >0: 51 ct-=1 52 if nxt is not None: 53 cur = nxt 54 nxt = nxt.nxt 55 56 else: 57 break 58 59 print("connect", cur, "to", prev) 60 cur.nxt = prev 61 prev = stay 62 63 stay = nxt 64 cur = nxt 65 self.head = prev 66 67 68 c = chain() 69 c.insert(1) 70 c.insert(2) 71 c.insert(3) 72 c.insert(4) 73 c.insert(5) 74 c.insert(6) 75 c.insert(7) 76 c.reverse_(3) 77 print(c)
Result:
1 connect 3 to None 4 connect 6 to 1 7 connect 7 to 4 7,4,5,6,1,2,3
Chatgpt:
要实现按 标签:202407017,Large,None,nxt,self,head,next,链表 From: https://www.cnblogs.com/PRCguardian/p/18307142