剑指Offer(Java版)第十九题:输入一个链表,反转链表后,输出链表的所有元素。

 

/*
输入一个链表,反转链表后,输出链表的所有元素。
*/
public class Class19 {

static class ListNode{
int val;
ListNode next = null;
ListNode(int val){
this.val = val;
}
}

//迭代法
public ListNode reverseList(ListNode head){
ListNode temp = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = temp;
temp = head;
head = next;
}
return temp;
}
//递归法
public ListNode reverseList2(ListNode head){
if(head == null || head.next == null){
return head;
}
ListNode newHead = reverseList2(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
//三个指针的方法
public ListNode reverseList3(ListNode head){
if(head == null){
return null;
}
ListNode pointNode = head;
ListNode preNode = null;
ListNode nextNode = pointNode.next;
while(nextNode != null){
pointNode.next = preNode;
preNode = pointNode;
pointNode = nextNode;
nextNode = pointNode.next;
}
pointNode.next = preNode;
return pointNode;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

}

}

posted on 2020-03-11 15:42  桌子哥  阅读(262)  评论(0编辑  收藏  举报