跟小D每日学口语

C#反转单向链表

 

    class Class1
    
{
        [STAThread]
        
static void Main(string[] args)
        
{
            
//初始化链表
            LineNote startnote = new LineNote( "1" );
            LineNote note 
= startnote;
            
forint i = 2; i<= 5 ;i ++ )
            
{
                note.Next 
= new LineNote( i.ToString() );
                note 
= note.Next;
            }

            note 
= startnote;
            
//输出
            while ( note!=null )
            
{
                System.Console.WriteLine( note.Note );
                note 
= note.Next;
            }

            
//开始反转
            note = startnote;
            LineNote temp 
= note;
            
while ( temp != null )
            
{
                note 
= startnote;
                
if ( temp != startnote )
                
{
                    startnote 
= temp;
                    temp 
= temp.Next;
                    startnote.Next 
= note;
                }

                
else
                
{
                    temp 
= temp.Next;
                    note.Next
= null;
                }

            }

            再次输出
            note 
= startnote;
            
while ( note!=null )
            
{
                System.Console.WriteLine( note.Note );
                note 
= note.Next;
            }

        }

    }


    
class LineNote
    
{
        
public string Note;
        
public LineNote Next;
        
public LineNote( string note)
        
{
            Note
=note;
        }

    }

 

 

        List reverse(List l)
        {
            if(!l)
                return l;
            list cur = l.next;
            list pre = l;
            list tmp;
            pre.next = null;
            while ( cur )
            {
                tmp = cur;
                cur = cur.next;
                tmp.next = pre;
                pre = tmp;
            }
            return tmp;
        }

posted @ 2010-08-04 15:33  简简单单幸福  阅读(498)  评论(0编辑  收藏  举报