试题16:反转链表

来源:互联网 发布:mindnode有windows版么 编辑:程序博客网 时间:2024/05/25 01:34
题目大致为:
    对于一个链表,反转该链表并返回头结点。
思路:
    主要是指针的操作,但是要注意不能断链。这里可以使用非递归的方式求解。
public class Test16 {public ListNode reverse(ListNode head){if (head==null) {return null;}ListNode reverseHead=head;ListNode pNext=null;ListNode pNode=head;while(pNode!=null){ListNode next=pNode.next;if (next==null) {reverseHead=pNode;}pNode.next=pNext;pNext=pNode;pNode=next;}          return reverseHead;}public static void main(String[] args) { // 构建链表          ListNode node1=new ListNode();          ListNode node2=new ListNode();          ListNode node3=new ListNode();          node1.val=1;          node2.val=2;          node3.val=3;          node1.next=node2;          node2.next=node3;          Test16 test=new Test16();         System.out.println(test.reverse(node1).val);}}

相似问题:
1. 求链表的中间节点    
使用两个指针,快慢指针同时从头结点出发,slow每次走一个,fast每次走两个结点。当fast到达链表末尾时,slow刚好到达链表中间节点。
2. 判断链表是否构成环
使用两个指针,slow与fast,判断slow==fast  返回true时则是有环,否则是无环。