题目描述
输入一个链表,反转链表后,输出新链表的表头。
代码
头插法。利用三个结点,pre head next进行操作。
借用一张图,加深理解
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null){
return head;
}
ListNode pre=null;
ListNode next=null;
while(head!=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
}
加一个双向链表的反转:
public static class DoubleNode {
public int value;
public DoubleNode last;
public DoubleNode next;
public DoubleNode(int data) {
this.value = data;
}
}
public static DoubleNode reverseList(DoubleNode head) {
DoubleNode pre = null;
DoubleNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
head.last = next;//比起单向链表就多了这一行
pre = head;
head = next;
}
return pre;
}