1,LeetCode206
/**
* 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
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null
ListNode cur = head
while(cur != null){
ListNode temp = cur.next
cur.next = pre
pre = cur
cur = temp
}
return pre
}
}
2,LeetCode204
/**
* 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
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head
}
ListNode pre = head
ListNode cur = head.next
int temp = 0
while(cur != null){
temp = pre.val
pre.val = cur.val
cur.val = temp
pre = pre.next.next
if(cur.next == null){
break
}else {
cur = cur.next.next
}
}
return head
}
}