public class ListNode {
public int val;
public ListNode next;
public ListNode(int val,ListNode next){
this.val = val;
this.next = next;
}
@Override
public String toString(){
StringBuilder sb = new StringBuilder(64);
sb.append("[");
ListNode p = this;
while (p!=null){
sb.append(p.val);
if (p.next!=null){
sb.append(",");
}
p = p.next;
}
sb.append("]");
return sb.toString();
}
}
方法一:
public ListNode reverseList(ListNode o1){
ListNode n1 = null;
ListNode p = o1;
while (p != null){
n1 = new ListNode(p.val,n1);//将得到的p,放入新链表的头部
p = p.next;
}
return n1;
}
public static void main(String[] args) {
ListNode o5 = new ListNode(5,null);
ListNode o4 = new ListNode(4,o5);
ListNode o3 = new ListNode(3,o4);
ListNode o2 = new ListNode(2,o3);
ListNode o1 = new ListNode(1,o2);
System.out.println(o1);
ListNode n1 = new code().reverseList(o1);
System.out.println(n1.toString());
}
方法二:
public class List {//容器类
ListNode head;
public List(ListNode head){
this.head = head;
}
public void addFirst(ListNode first){
first.next = head;
head = first;
}
public ListNode removeFirst(){
ListNode first = head;
if (first != null){
head = first.next;
}
return first;
}
}
public ListNode reverseList(ListNode head){
List list1 = new List(head);
List list2 = new List(null);
while (true){
ListNode first = list1.removeFirst();//遍历旧链表,挨着移除
if (first == null){
break;
}
list2.addFirst(first);//将旧链表的值放入新链表
}
return list2.head;
}
方法三:递归
public ListNode reverseList(ListNode p){
if (p == null || p.next == null){
return p; //最后结点
}
ListNode last = reverseList(p.next);
p.next.next=p;//建立各个值之间的关系
p.next=null;
return last;
}