44.Swap Nodes in Pairs

来源:互联网 发布:淘宝开店需要什么材料 编辑:程序博客网 时间:2024/05/16 06:07

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

分析:题目中要求不可以改变节点的值,只能通过交换节点的位置来做这个题目。做这个题目的关键是保证链表不能断,分析的时候要看清楚每个节点的指向。

/*提交通过:每次保证dump.next到node节点是已经交换好的,p和q是即将要交换的*/public ListNode swapPairs(ListNode head) {ListNode dump = new ListNode(0);dump.next = head;//增加一个额外的头结点,保证处理真正的头结点和后面一样ListNode node = dump;ListNode p = head;while (p != null && p.next != null) {ListNode q = p.next;node.next = q;node = p;p = q.next;q.next = node;node.next = p;}return dump.next;}
提交之后试着用交换节点值做了一遍(但是不符合leetcode题目要求)。

public ListNode swapPairs2(ListNode head) {//可以实现功能,但是不符合要求,这个方法是交换节点值得到ListNode p = head;while (p != null && p.next != null) {ListNode q = p.next;int temp = p.val;p.val = q.val;q.val = temp;p = q.next;}return head;}


0 0
原创粉丝点击