N15_反转链表后,输出新链表的表头。

题目描述

输入一个链表,反转链表后,输出新链表的表头。
package new_offer;
/**
 * 输入一个链表,反转链表后,输出新链表的表头。
 * @author Sonya
 *思路:遍历头插法。
 */
public class N15_ReverseList {
	public ListNode ReverseList(ListNode head) {
		if(head==null)return null;
		if(head.next==null)return head;
		ListNode p,q;
		p=head.next;
	    q=head;
	   q.next=null;
		while(p!=null) {
			ListNode k=p;
			p=p.next;//这句要放后面两句的前面
			k.next=q;
			q=k;			
		}
		return q;
    }

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		N15_ReverseList n15=new N15_ReverseList();
		ListNode listNode=new ListNode(1);
		ListNode L2=new ListNode(2);
		ListNode L3=new ListNode(3);
		ListNode L4=new ListNode(4);
		ListNode L5=new ListNode(5);
		listNode.next=L2;
		L2.next=L3;
		L3.next=L4;
		L4.next=L5;
		ListNode p;
		p=n15.ReverseList(listNode);
		System.out.println(p.val);
	}

}

  

原文地址:https://www.cnblogs.com/kexiblog/p/11076198.html