链接
思路
一、
将链表拆开进行尾插,同时要用一个新的头结点作为新的链表头
二、
将链表拆开进行头插
代码
一、
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head)
{
if (head == null)
{
return null;
}
if (head.next == null)
{
return head;
}
ListNode cur = head;
ListNode prev = null;
ListNode newHead = null;
while (cur != null)
{
ListNode temp = cur.next;
cur.next = prev;
if (temp == null)
{
newHead = cur;
}
prev = cur;
cur = temp;
}
return newHead;
}
}
二、
public ListNode reverseList(ListNode head)
{
if (head == null)
{
return null;
}
if (head.next == null)
{
return head;
}
ListNode cur = head;
ListNode prev = null;
while (cur != null)
{
ListNode temp = cur.next;
cur.next = prev;
prev = cur;
cur = temp;
}
return prev;
}