题目描述
输入一个链表,反转链表后,输出新链表的表头。
package com.hwx.swordToOffer._15_ReverseList;
/*
* 题目描述:
输入一个链表,反转链表后,输出新链表的表头。
*/
/*
* 思路:
* 另用两个变量:cur:始终保存新链表的头结点 next:当前结点的下一个结点
* 1)取出当前节点head
* 2)保存当前节点的下一个结点next
* 3)使取出的新结点指向cur
* 4)令head=next
* 循环以上操作
*/
public class Solution {
public static void main(String[] args) {
ListNode n1=new ListNode(1);
ListNode n2=new ListNode(2);
ListNode n3=new ListNode(3);
ListNode n4=new ListNode(4);
ListNode n5=new ListNode(5);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
ListNode newHead = ReverseList(n1);
newHead.print();
}
/*
* 表达更为简洁的方法
*/
public static ListNode ReverseList(ListNode head) {
ListNode cur=null;//保存新链表的头结点
ListNode next=null;//保存当前结点 的下一个结点。如果不用链表会断开。
while(head!=null) {
next=head.next;//保存当前节点的下一个结点
head.next=cur;//当前结点指向新链表的头结点
cur=head;//令cur重新指向新链表的头结点
//如果不用next节点保存下一个节点的话,直接head=head.next,此时为null,链表断开
head=next;
}
return cur;
}
/*
* 我的方法:和最佳方法思路是一样的,只是多用了一个变量newHead,不够简洁
* 方法1直接用head操作,节省空间
*/
public static ListNode ReverseList2(ListNode head) {
ListNode cur=null;
ListNode newHead=null;
ListNode next=null;
while(head!=null) {
newHead=head;
next=head.next;
newHead.next=cur;
cur=newHead;
head=next;
}
return newHead;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
public void print() {
ListNode cur=this;
while(cur!=null) {
System.out.println(cur.val);
cur=cur.next;
}
}
}