一、题目
二、代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution
{
//双指针确实巧妙
public ListNode reverseList(ListNode head)
{
if(head == null) return null;
ListNode temp;
ListNode pre = null;
ListNode cur = head;
//赋值前保存 不会联动改变
while(cur!=null)
{
temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
三、运行结果
四、附录
class Solution
{
public void reverseString(char[] s)
{
char temp = 0;
int length = s.length;
int i;
for(i=0;i<length/2;i++)
{
temp = s[i];
s[i] = s[length-1-i];
s[length-1-i] = temp;
}
}
}