35. 翻转链表
Description
Reverse a linked list.
Example
For linked list 1->2->3, the reversed linked list is 3->2->1
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
//Need three pointers
if (head== null || head.next==null){
return head;
}
ListNode prev = null;
ListNode curt = head;
while(curt != null){
ListNode temp = curt.next;
curt.next = prev;
prev = curt;
curt = temp;
}
return prev;
}
}
public class Solution {
/**
* @param head: n
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
// write your code here
ListNode prev = null;
while (head != null) {
ListNode temp = head.next;
head.next = prev;
prev = head;
head = temp;
}
return prev;
}
描述
翻转一个链表
您在真实的面试中是否遇到过这个题?
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成

浙公网安备 33010602011771号