【两两交换链表中的节点】

简介: 【两两交换链表中的节点】

正文


一、题目描述#


给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例:


给定 1->2->3->4, 你应该返回 2->1->4->3.


二、代码#


/**
 * 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 h,cur, pre, next;
        pre = head;
        h=pre;
        boolean isFirst=true;
        if (null != pre && null != pre.next) {
            cur = pre;
            while (null != cur && null != cur.next) {
                next = cur.next;
                cur.next = next.next;
                next.next = cur;
                if(isFirst){
                    pre = next;
                    h=pre;
                    isFirst=false;
                }else {
                    pre.next = next;
                }
                //向下
                pre = cur;
                cur=cur.next;
            }
        }
        return h;
    }
}
相关文章
|
1天前
24. 两两交换链表中的节点
24. 两两交换链表中的节点
|
5天前
|
存储
删除链表的节点
删除链表的节点
3 0
|
6天前
|
存储 SQL 算法
|
6天前
|
SQL 算法 数据挖掘
力扣题目 19:删除链表的倒数第N个节点 【python】
力扣题目 19:删除链表的倒数第N个节点 【python】
|
16天前
|
存储 Python
删除链表节点详解
删除链表节点详解
|
1月前
【移除链表元素】LeetCode第203题讲解
【移除链表元素】LeetCode第203题讲解
|
6天前
|
存储 SQL 算法
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
LeetCode力扣第114题:多种算法实现 将二叉树展开为链表
|
2天前
|
算法
【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
【经典LeetCode算法题目专栏分类】【第7期】快慢指针与链表
|
6天前
|
存储 SQL 算法
LeetCode 题目 86:分隔链表
LeetCode 题目 86:分隔链表
|
6天前
|
存储 SQL 算法
LeetCode 83题:删除排序链表中的重复元素【面试】
LeetCode 83题:删除排序链表中的重复元素【面试】