题解 | #反转链表#
反转链表
http://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
Java代码实现:
该算法的解题方法有多种,有迭代,递归,栈,新建链表等方法,其中迭代法比较容易理解
//1. 首先需要自定义一个链表,元素包含了val值和next指针,并自写一个构造方法ListNode【有时候会提供,但建议掌握一下,面试的时候一般不提供】
public class ListNode {
ListNode next = null;
ListNode next = null;
int value;
ListNode(int value) {
this.value = value;
}
}
ListNode(int value) {
this.value = value;
}
}
public class Solution {
public ListNode reverseList (ListNode head) {
ListNode pre = null; // 2.定义pre节点,让其指向反转以后的最后一个节点
ListNode cur = head; // 3.定义cur节点,让其指向原链表的起始节点
// 4. 循环遍历整个链表
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
//5. pre和cur节点位置依次往后移
pre = cur;
cur = next;
}
return pre;
}
}
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
//5. pre和cur节点位置依次往后移
pre = cur;
cur = next;
}
return pre;
}
}