链表反转:给定一个单链表,每k个为一组,一组内的元素反转。
如输入: 1-2-3-4-5-6-7-8,k=3,
输出:3-2-1-6-5-4-8-7。
==每个节点的指针地址不变,不能改值==
利用栈即可,什么特么的不仔细看题,自己给自己加戏,以为要改指针形成新链表,活该自己倒霉了
代码 python2:
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 16:13:38 2021
@author: 95136
"""
#不改变指针啊,傻逼了
import sys
#str = raw_input()
#print str
#print 'Hello,World!'
#arr=sys.stdin.readline()
class Node:
def __init__(self,val):
self.val=val
self.next=None
def transformLinkListByK(root,k):
count=0
ans=[]
templist=[]
head=None
tail=None
if not root:
return root
cur=root
while cur:
templist.append(cur)
cur=cur.next
count+=1
if count==k:
while templist:
ans.append(templist.pop().val)
count=0
while templist:
ans.append(templist.pop().val)
return ans
root=None
#nodelist=raw_input().split("-")
nodelist=['1','2','3','4','5','6','7','8']
#k=int(raw_input())
k=3
if nodelist:
root=Node(nodelist[0])
else:
raise(Exception("input invalid!"))
cur=root
for val in nodelist[1:]:
cur.next=Node(val)
cur=cur.next
arr=transformLinkListByK(root,k)
print "-".join(arr)
#下面放改指针的东西,比较复杂点,饶。
#然后牛客网有一题不一样,是最后剩下不满k的,不反转,维持原样,不一样的
python2代码
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 16:13:38 2021
@author: 95136
"""
import sys
#str = raw_input()
#print str
#print 'Hello,World!'
#arr=sys.stdin.readline()
class Node:
def __init__(self,val):
self.val=val
self.next=None
def transformLinkListByK(root,k):
count=0
templist=[]
head=None
tail=None
if not root:
return root
cur=root
while cur:
templist.append(cur)
cur=cur.next
count+=1
if count==k:
curhead,curtail = process(templist)
if not head:
head=curhead
tail=curtail
else:
tail.next=curhead
tail=curtail
templist=[]
count=0
if templist:
curhead,curtail = process(templist)
if not head:
head=curhead
tail=curtail
else:
tail.next=curhead
tail=curtail
tail.next=None
return head
def process(templist):
curhead=None
cur=None
curtail=None
while templist:
node=templist.pop()
if not cur:
cur=node
curhead=cur
else:
cur.next=node
cur=cur.next
if len(templist)<1:
curtail=node
#node.next=None
return curhead,curtail
root=None
#nodelist=raw_input().split("-")
nodelist=['1','2','3','4','5','6','7','8']
#k=int(raw_input())
k=3
if nodelist:
root=Node(nodelist[0])
else:
raise(Exception("input invalid!"))
cur=root
for val in nodelist[1:]:
cur.next=Node(val)
cur=cur.next
head=transformLinkListByK(root,k)
arr=[]
cur=head
while cur:
arr.append(cur.val)
cur=cur.next
print "-".join(arr)