1、单链表的倒置的C#实现。
思路:从头节点开始以此将节点的指向倒转,最后返回原链表的尾节点也就是倒转后链表的头节点。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingleDirtempnode
{
/// <summary>
/// 模拟链表节点
/// </summary>
class Linktempnode
{
public object data;
public Linktempnode next;
public Linktempnode(object adata)
{
this.data = adata;
}
}
class Program
{
/// <summary>
/// 反转函数
/// </summary>
/// <param name="tempnode"></param>
/// <returns></returns>
public static Linktempnode Inverse(Linktempnode tempnode)
{
// r,q,p 一步一步,像走路一样
// p总是指向下一个节点
//q 用来跟上p
//r 用来存储断开的节点
Linktempnode r = null;
Linktempnode q = null;
Linktempnode p = tempnode;
while (p != null)
{
r = q;
q = p;
p = p.next;
q.next = r;
}
return q;
}
/// <summary>
/// 打印单链表
/// </summary>
/// <param name="list"></param>
public static void PrintList(Linktempnode list)
{
Linktempnode p = list;
while (p != null)
{
Console.WriteLine(p.data);
p = p.next;
}
}
static void Main(string[] args)
{
Linktempnode n1 = new Linktempnode("1");
Linktempnode n2 = new Linktempnode("2");
Linktempnode n3 = new Linktempnode("3");
Linktempnode n4 = new Linktempnode("4");
Linktempnode n5 = new Linktempnode("5");
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
Console.WriteLine("before reverse:");
PrintList(n1);
Console.WriteLine("after reverse:");
Linktempnode head = Inverse(n1);
PrintList(head);
Console.Read();
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SingleDirtempnode
{
/// <summary>
/// 模拟链表节点
/// </summary>
class Linktempnode
{
public object data;
public Linktempnode next;
public Linktempnode(object adata)
{
this.data = adata;
}
}
class Program
{
/// <summary>
/// 反转函数
/// </summary>
/// <param name="tempnode"></param>
/// <returns></returns>
public static Linktempnode Inverse(Linktempnode tempnode)
{
// r,q,p 一步一步,像走路一样
// p总是指向下一个节点
//q 用来跟上p
//r 用来存储断开的节点
Linktempnode r = null;
Linktempnode q = null;
Linktempnode p = tempnode;
while (p != null)
{
r = q;
q = p;
p = p.next;
q.next = r;
}
return q;
}
/// <summary>
/// 打印单链表
/// </summary>
/// <param name="list"></param>
public static void PrintList(Linktempnode list)
{
Linktempnode p = list;
while (p != null)
{
Console.WriteLine(p.data);
p = p.next;
}
}
static void Main(string[] args)
{
Linktempnode n1 = new Linktempnode("1");
Linktempnode n2 = new Linktempnode("2");
Linktempnode n3 = new Linktempnode("3");
Linktempnode n4 = new Linktempnode("4");
Linktempnode n5 = new Linktempnode("5");
n1.next = n2;
n2.next = n3;
n3.next = n4;
n4.next = n5;
Console.WriteLine("before reverse:");
PrintList(n1);
Console.WriteLine("after reverse:");
Linktempnode head = Inverse(n1);
PrintList(head);
Console.Read();
}
}
}