使用和不使用递归来反转单链接列表

时间:2010-01-15 09:38:48

标签: c# algorithm data-structures singly-linked-list

我是数据结构的新手,我知道这是一个非常常见的问题。但是我知道.NET中的LinkedList是双重链接的,所以我将如何为C#中的单链表编写代码。

有人可以写一些示例代码吗?

7 个答案:

答案 0 :(得分:2)

这是使用递归。

private void Reverse(Item item)
    {
        if (item == null || item.Next == null) //if head is null or we are at the tail
        {
            this.Head = item; //we are at the tail or empty list, set the new head to the tail
            return;
        }

        Reverse(item.Next);

        var nextItem = item.Next; //get the next item out, dealing with references don't want to override it
        item.Next = null;         //once you get the next item out, you can delete the *reference* i.e. link to it
        nextItem.Next = item;     //set the item you got out link to next item to the current item i.e. reverse it
    }

答案 1 :(得分:1)

使用循环(当前元素:currentNode,变量initialzied outside loop:previousNode,nextNode)

Set nextNode = currentNode.NextNode
Set currentNode.NextNode = previousNode
Set previousNode = currentNode
Set currentNode = nextNode
continue with loop

答案 2 :(得分:0)

您需要定义一个节点数据结构,其中包含一些数据和对链接列表中下一个节点的引用。类似的东西:

class Node {
  private Node _next;
  private string _data;

  public Node(string data) {
    _next = null;
    _data = data;
  }

  // TODO: Property accessors and functions to link up the list
}

然后你可以写一个算法以相反的顺序遍历列表,构建一个新的反向列表。

答案 3 :(得分:0)

reversed_list = new
for all node in the original list
   insert the node to the head of reversed_list

答案 4 :(得分:0)

由于这可能是家庭作业,我将以一种可能非常混乱的方式陈述这一点,以免完成所有工作。希望我的尝试不仅会让事情变得更加混乱(这很有可能)。

如果您对列表中的节点(比如第一个节点)有引用,那么您还可以引用它后面的节点。您只需要让以下节点引用当前节点,同时保留有关以下节点(及其先前状态)的足够信息,以便为其执行类似的工作。现在唯一棘手的部分是处理边界条件(列表的开始和结束)。

答案 5 :(得分:0)

//Have tried the Iterative approach as below, feel free to comment / optimize 

package com.test;


public class ReverseSinglyLinkedList {


public ReverseSinglyLinkedList() {
    // TODO Auto-generated constructor stub
}
public Node ReverseList(Node n)
{

    Node head =  n; 
    Node current = n; 
    Node firstNodeBeforeReverse = n;  // keep track of origional FirstNode

    while(true) 
    {

        Node temp = current; 
         // keep track of currentHead in LinkedList "n", for continued access to unprocessed List
        current = current.next; 
        temp.next = head;
          // keep track of head of Reversed List that we will return post the processing is over 
        head = temp;   

        if(current.next == null)
        {

            temp = current;
            current.next = head;
            head = temp;        
                            // Set the original FirstNode to NULL
            firstNodeBeforeReverse.next = null; 

            break;
        }
    } 

    return head;

}

public void printLinkList(Node n)
{

    while(true)
    {
        System.out.print(n.data + " ");
        n = n.next;
        if(n.next ==null)
        {
            System.out.print(n.data + " ");
            break;
        }

    }
}

public static void main(String[] args) {
    // TODO Auto-generated method stub

    // TEST THE PROGRAM: crate a node List first to reverse it
    Node n = new Node(1);
    n.next = new Node(2);
    n.next.next = new Node(3);
    n.next.next.next = new Node(4);
    n.next.next.next.next = new Node(5);
    n.next.next.next.next.next = new Node(6);

    ReverseSinglyLinkedList r = new ReverseSinglyLinkedList();
    System.out.println("Input Linked List : ");  
    r.printLinkList(n);

    Node rsList = r.ReverseList(n);

    System.out.println("\n Reversed Linked List : ");
    r.printLinkList(rsList);



}

}

答案 6 :(得分:0)

这是在.net(C#)中链接反转迭代和递归 (注意链表是维护第一个和最后一个指针,以便我可以在末尾追加或在O(1)中插入头部 - 一个不必这样做。我只是如上所述定义了我的链表行为)< / p>

public void ReverseIterative()
        {
            if(null == first)
            {
                return;
            }
            if(null == first.Next)
            {
                return;
            }
            LinkedListNode<T> p = null, f = first, n = null;
            while(f != null)
            {
                n = f.Next;
                f.Next = p;
                p = f;
                f = n;
            }
            last = first;
            first = p;
        }

<强>递归:

        public void ReverseRecursive()
        {
            if (null == first)
            {
                return;
            }
            if (null == first.Next)
            {
                return;
            }
            last = first;
            first = this.ReverseRecursive(first);
        }
        private LinkedListNode<T> ReverseRecursive(LinkedListNode<T> node)
        {
            Debug.Assert(node != null);
            var adjNode = node.Next;
            if (adjNode == null)
            {
                return node;
            }
            var rf = this.ReverseRecursive(adjNode);
            adjNode.Next = node;
            node.Next = null;
            return rf;
        }