最近学校在弄125年校庆,官方微信公众号还推出了校庆头像框的活动,我这个老腊肉自然是要来不知羞耻的凑个热闹啦!请各位看官看下图,不喜勿喷哈,我心脏比较小,啊哈哈哈哈哈。
24-两两交换链表中的节点
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
实例:
给定1->2->3->4, 其结果为2->1->4->3
说明:
- 你的算法只能使用常数的额外空间。
- 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
这一题我刚开始是想用双指针来解题的,即first指针指向给定的head指针表头,second指针指向first指针的后一个节点,再新建一个指针专门顺序接受second->first这两个指针所对应的值,最后即可得所要结果。但这其中有个小障碍就是一定一定要处理好first和second指针的指向问题,因为这两个指针都是指向head指针的,一旦没有指向好,就得不出结果的。今天刚好有一笔友问了我这方面的问题,于是就想了一会儿终于是把之前留下的烂摊子给解决了,由于他是用java写的,所以我就也用java写了。
代码如下:
class Solution {
public ListNode swapPairs(ListNode head) {
ListNode virtual=new ListNode(0);
if(head==null || head.next==null)
return head;
ListNode baseRear=virtual;
ListNode rear=head;
ListNode front=head.next;
while(rear!=null && front!=null)
{
baseRear.next= new ListNode(front.val);
baseRear.next.next = new ListNode(rear.val);
baseRear=baseRear.next.next;
if(front.next != null) {
rear=front.next;
front=rear.next;
}else {
rear = front = null;
}
}
if(rear!=null) {
baseRear.next= new ListNode(rear.val);
baseRear=baseRear.next;
}
return virtual.next;
}
}
public class JTest2 {
public static void main(String[] args) {
int head_list[] = {1, 2, 5, 4, 7};
ListNode head = new ListNode(0);
ListNode head_copy = head;
for (int i = 0; i < head_list.length; i++) {
head_copy.next = new ListNode(head_list[i]);
head_copy = head_copy.next;
}
Solution solu = new Solution();
ListNode result = solu.swapPairs(head.next);
while (result != null) {
System.out.println(result.val);
result = result.next;
}
}
}
下面是我那作图一流的笔友提供的指针指向图,很形象生动,方便大家理解。
执行效率当然也是棒棒哒!
还有一种方法是我用单指针解决的,当时就是被双指针搞糊涂了,所以就想用单指针解决,但其实思想还是和双指针的思想是一样的,只不过我这儿是用单指针来分别表示first和second指针的,这儿就是用python写的。
代码如下:
class Solution:
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return []
head_copy = head
head_sort = ListNode(0)
head_sort_copy = head_sort
while head_copy.next:
head_sort_copy.next = ListNode(head_copy.next.val)
head_sort_copy = head_sort_copy.next
head_sort_copy.next = ListNode(head_copy.val)
head_sort_copy = head_sort_copy.next
if head_copy.next.next:
head_copy = head_copy.next.next
else:
break
if head_copy and head_copy.next is None:
head_sort_copy.next = head_copy
return head_sort.next
if __name__ == '__main__':
head_num = [2, 1, 3, 4, 8, 9]
head = ListNode(0)
head_copy = head
for num in head_num:
head_copy.next = ListNode(num)
head_copy = head_copy.next
result = Solution().swapPairs(head.next)
while result:
print(result.val)
result = result.next
执行效率比上面的双指针方法还要高些。