【LeetCode】Swap Nodes in Pairs 链表指针的应用

来源:互联网 发布:沈阳seo那家好 编辑:程序博客网 时间:2024/06/07 23:22

题目:swap nodes in pairs

<span style="font-size:18px;">/** * LeetCode Swap Nodes in Pairs  * 题目:输入一个链表,要求将链表每相邻的两个节点交换位置后输出 * 思路:遍历一遍即可,时间复杂度O(n) * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */package javaTrain; public class Train12 {public ListNode swapPairs(ListNode head) {if(head == null || head.next == null) return null;        ListNode pNode;        pNode = head;        while(pNode != null && pNode.next != null){        int temp;         temp = pNode.val;        pNode.val = pNode.next.val;        pNode.next.val = temp;        pNode = pNode.next.next;         }        return head;    }}</span>


1 0
原创粉丝点击