输入一个偶数n(n>2),建立不带头结点的整数单链表L,L=(a1,an,a2,an-1,...,an-2,...an),其中ai=i
时间: 2023-05-30 10:05:51 浏览: 242
首先,我们需要确定链表的长度,因为链表中的元素是按照一定的规律排列的。因为题目中给定的是偶数n,所以链表的长度为n。
其次,我们需要考虑链表中每个元素的值。根据题目要求,链表中的第一个元素为1,第二个元素为n,第三个元素为2,第四个元素为n-1,以此类推,直到链表中倒数第二个元素为n/2,最后一个元素为n/2+1。
因此,我们可以按照上述规律依次构造链表。
代码如下:
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def createList(n):
head = None
tail = None
for i in range(1, n//2+1):
node1 = ListNode(i)
node2 = ListNode(n-i+1)
if not head:
head = node1
tail = node2
head.next = tail
else:
node1.next = tail
tail.next = node2
tail = node2
tail.next = None
return head
```
我们可以测试一下:
```python
head = createList(8)
while head:
print(head.val)
head = head.next
```
输出结果为:
```
1
8
2
7
3
6
4
5
```
阅读全文
相关推荐







