描述:
翻转一个链表
样例:
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
Java代码:
一个指针指旧list
一个指针指新list
一个临时指针
头插法
/**
* Definition for ListNode.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int val) {
* this.val = val;
* this.next = null;
* }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode newList = null;
ListNode oldList = null;
ListNode temp = null;
boolean isFirstNode = true;
if(head != null){
newList = head;
oldList = head.next;
}
while(oldList!= null){
//第一个节点的处理
if(isFirstNode){
newList.next = null;
isFirstNode = false;
}
temp = oldList;
oldList = oldList.next;
//头插法
temp.next = newList;
newList = temp;
}
return newList;
}
}