首页 > 试题广场 >

翻转链表

[编程题]翻转链表
  • 热度指数:5701 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

对于一个链表 L: L0→L1→…→Ln-1→Ln,
将其翻转成 L0→Ln→L1→Ln-1→L2→Ln-2→…

输入是一串数字,请将其转换成单链表格式之后,再进行操作


输入描述:
一串数字,用逗号分隔


输出描述:
一串数字,用逗号分隔
示例1

输入

1,2,3,4,5

输出

1,5,2,4,3

备注:
数组长度不超过100000
import sys
class ListNode:
    def __init__(self, n):
        self.val = n
        self.next = None
ls = list(map(int, sys.stdin.readline().strip().split(',')))
lst = [n for n in ls]
new_lst = []
n = len(lst)-1
for i in range(int(len(lst)/2)):
    new_lst.append(lst[i])
    new_lst.append(lst[n-i])
if len(lst)%2 >0:
    new_lst.append(lst[int(len(lst)/2)])
ans =''
new_lst = [ListNode(n) for n in new_lst]
for i,node in enumerate(new_lst):
    if i<len(new_lst)-1:
        node.next = new_lst[i+1]
        ans += str(node.val) +','
    else:
        ans += str(node.val)
print(ans)
发表于 2020-07-26 16:19:18 回复(0)
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution:
    def link(self,seq):
        if not seq:return None
        head=ListNode(0)
        cur=head
        for i in seq:
            cur.next=ListNode(i)
            cur=cur.next
        return head.next

    def reorderList(self, head) :
        #对特殊用例进行判断
        if not head :return None
        #对链表进行二分段
        fast=slow=head
        while fast and fast.next:
            slow=slow.next
            fast=fast.next.next
        middle=slow.next
        slow.next=None

        #对第二段进行反转
        pre,cur=None,middle
        while cur:
            cur.next,pre,cur=pre,cur,cur.next

        #将两段合并
        cur=head
        while pre:
            cur.next,pre.next,pre,cur=pre,cur.next,pre.next,cur.next

        return head

if __name__=='__main__':
    seq=list(map(int,input().split(',')))
    s=Solution()
    head=s.link(seq)
    cur=s.reorderList(head)
    ans=[]
    while cur:
        ans.append(cur.val)
        cur=cur.next
    print(*ans,sep=',')




编辑于 2020-02-17 10:01:08 回复(0)
#整体思路是:
#先根据输入初始化成一个单链表
#然后复制一个刚生成的链表
#把其中一个链表进行反转
#按照链表长度的一半次数合并两个链表,即可生成题目要求的链表
class Node(object):
    def __init__(self,val):
        self.val = val
        self.next = None
class ClainList(object):
    #初始化列表
    def __init__(self,list):
        self.count = 0
        if not list:
            return None
        self.head = None
        cur = None
        for i in list:
            if cur == None:
                self.head = Node(i)
                cur = self.head
            else:
                temp = Node(i)
                cur.next = temp
                cur = temp
            self.count += 1
    def reverse(self,head):
        #反转链表
        if not head:
            return None
        pre = head
        if head.next == None:
            return head
        cur = head.next
        head.next = None
        if cur.next == None:
            cur.next = pre
            return cur
        post = cur.next
        while cur!=None:
            cur.next = pre
            if post == None:
                break
            pre = cur
            cur = post
            post=post.next
        return cur
    def series(self,head):
        #把链表以字符串形式输出
        res = []
        cur = head
        while cur:
            res.append(cur.val)
            cur = cur.next
        print(','.join(map(str,res)))
    def copy(self,head):
        #复制一个新的链表
        if not head:
            return None
        new_head = Node(head.val)
        cur1 = head
        cur2 = new_head
        while cur1:
            cur1 = cur1.next
            if cur1:
                temp = Node(cur1.val)
            else:
                temp = None
            cur2.next = temp
            cur2 = temp
        return new_head
    def combine(self,head1,head2,n):
        #把两个顺序相反的链表合并成题目要求
        if not head1 and not head2:
            return None
        cur1 = head1
        cur2 = head2
        post1 = head1.next
        post2 = head2.next
        new_cur = None
        new_head = None
        c = n//2
        for i in range(c):
            if new_head == None:
                new_head = cur1
                new_cur = cur1
            else:
                new_cur.next = cur1
                new_cur = new_cur.next
            new_cur.next = cur2
            new_cur = new_cur.next
            cur1 = post1
            cur2 = post2
            if not post1&nbs***bsp;not post2:
                break
            post1 = post1.next
            post2 = post2.next
        if n == 1:
            new_head = new_cur = head1
        elif n%2 == 1:
            new_cur.next = cur1
            new_cur = cur1
        new_cur.next = None
        return new_head
def main():
    array = map(int,input().split(','))
    s = ClainList(array)
    n = s.count
    head1 = s.copy(s.head)
    head2 = s.reverse(s.head)
    res = s.combine(head1,head2,n)
    s.series(res)
main()

发表于 2019-12-03 21:46:17 回复(0)
48 ms 10408K Python 3
s = input().split(',')
t = len(s)
r = t//2
o = []

def f(a): 
    x,y = s[:r],s[r+a:][::-1] # 拆分翻转
    for i in range(r):
        o.extend([x[i],y[i]])
    if a: o.append(s[r])

if t%2 == 1: f(1)
else: f(0)

print(','.join(o))

65 ms 9740K Python 3
s = input().split(',')
t = len(s)
d = t // 2
o = []

for i in range(d):
    o.extend([s[i],s[-i-1]])

if 2*d != t:
    o.append(s[d])

print(','.join(o))

769 ms 9412K Python 3
a = input().split(',')
# 反复横跳
c = [a.pop(-1) if i%2==1 else a.pop(0) for i in range(len(a))]
print(','.join(c))
编辑于 2019-11-02 03:09:47 回复(0)