原题
- 题目描述: 给定链表,交换每两个相邻节点并返回其头部。
- 思路:
- 自己构造一个头结点,定义一个cur指针,指向头结点.定义两个指针first和second
- 遍历链表,
first
指向cur.next
,second
指向cur.next.next
first.next
指向second
- 用
cur
指针串联起链表,即cur.next
指向second
,second.next
指向first
cur
指向first
,进行下一次循环
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode realHead=new ListNode(-1);
realHead.next=head;
ListNode cur=realHead;
ListNode first=null;
ListNode second=null;
while(cur.next!=null&&cur.next.next!=null){
first=cur.next;
second=cur.next.next;
first.next=second.next;
cur.next=second;
second.next=first;
cur=first;
}
return realHead.next;
}
}