【发布时间】:2020-08-16 13:08:04
【问题描述】:
我在 C# 中制作了一个链接列表程序,但我还想反转链接列表中的数字。程序运行并让我将数字添加到列表中,但是一旦我添加了数字,数字不会出现在反向部分,它只会输出“反向列表”。如何以相反的顺序显示数字?
using System;
namespace LinkedList
{
class Program
{
public class Node
{
public int data;
public Node next;
};
static Node add(Node head, int data)
{
Node temp = new Node();
Node current;
temp.data = data;
temp.next = null;
if (head == null)
head = temp;
else
{
current = head;
while (current.next != null)
current = current.next;
current.next = temp;
}
return head;
}
static void reverse_list(Node head)
{
Node prev = null, current = head, next = null;
while (current != null)
next = current.next;
current.next = prev;
prev = current;
current = next;
}
static void print_numbers(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
static Node List(int[] a, int n)
{
Node head = null;
for (int i = 1; i <= n; i++)
head = add(head, a[i]);
return head;
}
public static void Main(String[] args)
{
int n = 10;
int[] a;
a = new int[n + 1];
a[0] = 0;
Console.WriteLine("Add values to the list");
for (int i = 1; i <= n; i++)
a[i] = int.Parse(Console.ReadLine());
Node head = List(a, n);
Console.WriteLine("Linked List: ");
print_numbers(head);
Console.ReadLine();
Console.WriteLine();
Console.WriteLine("Reversed list: ");
reverse_list(head);
print_numbers(head);
}
}
}
【问题讨论】:
-
将其实现为双向链表会不会更简单,其中每个节点都链接到 prev 和 next,然后通过调用 prev prev prev 而不是 next 来枚举它下一个?它只需要一行代码就可以完成链接(在
current.next = temp;将列表的当前末尾链接到传入元素之后,有一个temp.prev = current将新传入节点链接回当前尾部)跨度> -
(哦,你需要另一行代码来跟踪尾节点;你真的不想先寻找它的末尾)
-
在 C# 编码约定中,公共成员的名称应该像这样
标签: c# linked-list singly-linked-list