C#链表从链表尾到链表头逆序输出
时间: 2023-12-02 08:42:27 浏览: 38
以下是C#链表从链表尾到链表头逆序输出的方法:
```csharp
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
LinkedList<int> list = new LinkedList<int>();
list.AddLast(1);
list.AddLast(2);
list.AddLast(3);
list.AddLast(4);
LinkedListNode<int> node = list.Last;
while (node != null)
{
Console.WriteLine(node.Value);
node = node.Previous;
}
}
}
```
输出结果为:
```
4
3
2
1
```
相关问题
链表从链表尾到链表头逆序输出
以下是两种Python实现链表逆序输出的方法:
1. 借助一个新的空链表
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
new_head = None
while head:
temp = head.next
head.next = new_head
new_head = head
head = temp
return new_head
# 测试
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
s = Solution()
new_head = s.reverseList(node1)
while new_head:
print(new_head.val)
new_head = new_head.next
```
2. 在原链表上直接逆序
```python
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
last = None
while head:
temp = head.next
head.next = last
last = head
head = temp
return last
# 测试
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3
s = Solution()
new_head = s.reverseList(node1)
while new_head:
print(new_head.val)
new_head = new_head.next
```
链表从链表尾到链表头逆序输出,语言描述
以下是链表从链表尾到链表头逆序输出的两种方法:
1. 使用栈:将链表中的每个节点依次入栈,然后再依次出栈输出即可实现链表从尾到头的逆序输出。
```C++
void reversePrint(ListNode* head) {
stack<ListNode*> s;
ListNode* p = head;
while (p != nullptr) {
s.push(p);
p = p->next;
}
while (!s.empty {
p = s.top();
s.pop();
cout << p->data << " ";
}
}
```
2. 递归:从链表头开始递归输出,当递归到链表尾时开始输出,这样就可以实现链表从尾到头的逆序输出。
```C++
void reversePrint(ListNode* head) {
if (head == nullptr) {
return;
}
reversePrint(head->next);
cout << head->data << " ";
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)