反转链表
知识点:链表反转
题目:
输入一个链表,输出该链表中倒数第k个结点。。
解析:
-
思路:
1 -> 2 -> 3 -> 4 -> 51 <- 2 <- 3 4 -> 5
使用两个指针 pre 和 next , pre代表前一段链表,next表示head的下一个链表
代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if (head == null)
return null;
//前一个结点
ListNode pre = null;
//后一个结点
ListNode next = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}