赞
踩
- class Solution {
- public:
- ListNode* ReverseList(ListNode* pHead) {
- ListNode *pre=nullptr;
- ListNode *cur=pHead;
- ListNode *nex=nullptr;
- while(cur)
- {
- nex=cur->next;
- cur->next=pre;
- pre=cur;
- cur=nex;
-
- }
- return pre;
-
-
- }
- };

思考:翻转链表是最基本的链表操作,可以用栈来中转,然后一次弹出的结果;
最普通的方法就是:
1、记录当前节点、下一节点、上一节点
2、流程:下一节点指向cur.next
当前节点的下一节点指向上一节点
上一节点后移、当前节点后移
- import java.util.*;
-
- /*
- * public class ListNode {
- * int val;
- * ListNode next = null;
- * }
- */
-
- public class Solution {
- /**
- *
- * @param head ListNode类
- * @param m int整型
- * @param n int整型
- * @return ListNode类
- */
- public ListNode reverseBetween (ListNode head, int m, int n) {
- // write code here
-
- ListNode dump = new ListNode(-1);
- dump.next = head;
- ListNode left = dump;
- ListNode right = dump;
- for (int i = 0; i < m-1 ; i++) {
- left = left.next;
- }
- for (int i = 0; i < n; i++)
- {
- right = right.next;
- }
- ListNode newhead = left.next;
- left.next = null;
-
- ListNode oldright = right.next;
- right.next=null;
-
- rever(newhead,n-m);
-
- newhead.next=oldright;
- left.next=right;
- return dump.next;
- }
- public void rever(ListNode head,int num){
- ListNode cur = head;
- ListNode pre = null;
- for(int i=0;i<num+1;i++){
- ListNode next = cur.next;
- cur.next=pre;
- pre = cur;
- cur = next;
- }
- }
- }

解决方法:
将链表翻转作为函数,先找出中间需要翻转的位置,要记录好断开处的位置,然后将需要反转的链表头以及长度传入,反转之后在接入原来的链表
- import java.util.*;
-
- /*
- * public class ListNode {
- * int val;
- * ListNode next = null;
- * }
- */
-
- public class Solution {
- /**
- *
- * @param head ListNode类
- * @param k int整型
- * @return ListNode类
- */
- public ListNode reverseKGroup (ListNode head, int k) {
- // write code here
- ListNode dump = new ListNode(-1);
- dump.next = head;
- ListNode end = dump;
- ListNode pre = dump;
-
- while(end.next!=null){
- for(int i=0;i<k&&end!=null;i++){
- end=end.next;
- }
- if(end==null){
- break;
- }
- ListNode start = pre.next;
- ListNode next = end.next;
-
- end.next=null;
-
- pre.next = rever(start);
- start.next = next;
- pre = start;
- end = start;
-
- }
- return dump.next;
-
- }
- public ListNode rever(ListNode head){
- ListNode cur = head;
- ListNode pre = null;
- while(cur!=null){
- ListNode next = cur.next;
- cur.next = pre;
- pre = cur;
- cur = next;
- }
- return pre;
- }
- }

解决方法:
外部的while循环控制链表的循环、里面的for循环控制k个为一组的循环,循环变量就是一个一个遍历链表节点,当够了k个尾一组就记下这一组的前一个节点,以及后一个节点,然后调用翻转函数,这个翻转函数和前面的不同,需要返回翻转后的头结点,链表翻转后的头是返回的新头,尾是翻转前传的头,这样将尾和之前记录的后一个节点连接回原链表继续遍历。
当然翻转链表这个功能同样可以用队列或者栈来实现。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。