反转单链表

 

1. 非递归 - 无头结点

 1         /// <summary>
 2         /// 非递归 - 无头结点
 3         /// </summary>
 4         /// <param name="head"></param>
 5         public static ListNode ReverseList(ListNode head)
 6         {
 7             if (head == null)
 8                 return null;
 9 
10             ListNode newHead = head;
11             ListNode temp =null;
12 
13             head = head.Next;
14             newHead.Next = null;
15 
16             while (head != null)
17             {
18                 temp = newHead;
19                 newHead = head;
20                 head = head.Next;
21                 newHead.Next = temp;
22             }
23 
24             return newHead;
25         }

2. 非递归 - 有头结点

 1         /// <summary>
 2         /// 非递归 - 有头结点
 3         /// </summary>
 4         /// <param name="head"></param>
 5         public static ListNode ReverseList(ListNode head)
 6         {
 7             if (head == null)
 8                 return null;            
 9 
10             ListNode newHead = new ListNode(head.Value);
11             ListNode temp =null;
12 
13             while (head.Next != null)
14             {
15                 temp = newHead.Next;
16                 newHead.Next = head.Next;
17                 head.Next = head.Next.Next;
18                 newHead.Next.Next = temp;
19             }
20 
21             return newHead;
22         }

3. 递归 - 无头结点

 1         /// <summary>
 2         /// 递归
 3         /// </summary>
 4         /// <param name="head"></param>
 5         public static ListNode ReverseList(ListNode head)
 6         {
 7             if (head == null || head.Next == null)
 8                 return head;
 9 
10             ListNode newHead = ReverseList(head.Next);
11 
12             head.Next.Next = head;
13             head.Next = null;
14 
15             return newHead;
16         }

 

posted @ 2015-09-23 20:20  叫我霍啊啊啊  阅读(161)  评论(0编辑  收藏  举报