【IT笔试面试题整理】反转链表

【试题描述】定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点

【参考代码】

方法一:

 1     public static Link reverseLinkList(Link head)
 2     {
 3         if (head == null || head.next == null)
 4             return head;
 5 
 6         Link pre = null;
 7         Link cur = head;
 8         Link back = head.next;
 9 
10         while (back != null)
11         {
12             cur.next = pre;
13             pre = cur;
14             cur = back;
15             back = back.next;
16         }
17         cur.next = pre; // 当current为最后一个节点时,back为null,所以要再指向前节点
18         head = cur;
19 
20         return head;
21     }

 

方法二:

 1     public static Link reverseLinkList2(Link head)
 2     {
 3         if (head == null || head.next == null)
 4             return head;
 5         Link p1 = head;
 6         Link p2 = p1.next;// p2其实记录的下一步递归过程后的尾结点
 7         head = reverseLinkList2(p2);
 8         p2.next = p1;
 9         p1.next = null;
10         return head;
11     }

 

posted @ 2013-04-11 19:46  曾先森在努力  阅读(198)  评论(0编辑  收藏  举报