题目:
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.
本题相对比较简单,就是交换相邻两个元素的位置,可以使用遍历法和递归法两种方法,递归法使用两个指针记录当前要交换位置的节点,在使用另外一个指针记录他们前面的那个节点。这样就可以很方便的实现节点位置的交换,然后在给三个指针更新值即可。代码入下:
public ListNode swapPairs(ListNode head) {ListNode pHead = new ListNode(0); = head;ListNode cur = pHead, next;while(head != null && != null){next = ; = ; = = head;cur = head;head = ;};}
递归法就更简单了,只需要实现交换两个节点位置的功能即可,代码如下所示:
public ListNode swapPairs1(ListNode head) {if ((head == null)||( == null))return head;ListNode n = ; = ext);n.next = head;return n;}
本文发布于:2024-01-29 18:15:25,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170652332717346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |